是否强制将所有子元素嵌套到其父元素中?请看一下我的示例代码。我看过一些文章,他们警告说嵌套子元素只能达到4个级别。但是在这里我把所有的孩子都包装到了它的父类。像这样编写sass代码可以吗?
<div class="col-md-3 left-side">
<div class="profile-info">
<img src="img/user.jpg" alt="">
<div class="info">
<p>Header</p>
<span>2 minutes ago</span>
</div>
</div>
<div class="ads">
<h4>Advertisements</h4>
<img src="img/ad1.jpg" alt="">
<p>Grab your book !!!</p>
<img src="img/ad2.jpg" alt="">
<p>Hurry up. Limited offers !!!</p>
<img src="img/ad3.jpg" alt="">
<p>Grab your book !!!</p>
<img src="img/ad4.jpg" alt="">
<p>Hurry up. Limited offers !!!</p>
</div>
</div>
.left-sidebar{
height: auto;
background-color: #fff;
.ads{
img{
width:100%;
}
h4{
margin-top:45px;
margin-top: 45px;
font-weight: 600;
}
p{
margin-top: 5px;
font-weight: 500;
margin-bottom: 22px;
}
}
.profile-info{
@include basic_style;
padding-top: 31px;
.info{
padding-top: 28px;
padding-left: 16px;
display: inline-block;
@media only screen and (max-width: 1200px){
padding-top: 20px;
padding-left: 0px;
text-align: center;
display: block;
}
}
img{
width: 100px;
height: 100px;
border-radius: 50%;
float: left;
@media only screen and (max-width: 440px){
width: 85px;
height: 85px;
}
@media only screen and (max-width: 1200px){
display: block;
margin: 0 auto;
float: none;
}
}
p{
@include post_title;
}
span{
@include sub_header;
}
}
}发布于 2016-09-29 18:38:51
这段代码的问题在于,您不能在右侧栏或其他地方使用.ads或.profile-info块。您的代码依赖于上下文。
要改善这种情况,您可以阅读有关BEM (块元素修改器)的内容。
在您的情况下,首先应该删除.left-sidebar选择器。其次,tad选择器不好用,所以在内部跨度、图像和段落中添加类名。
您的代码将如下所示:
.left-sidebar {
height: auto;
background-color: #fff;
}
.ads {
.img {
width:100%;
}
.h4 { // .h4 is just an example, write some more meaningful name
margin-top:45px;
margin-top: 45px;
font-weight: 600;
}
.p {
margin-top: 5px;
font-weight: 500;
margin-bottom: 22px;
}
}
// styles for .profile-info但是这个scss生成了不必要的二级选择器,比如.ads .img {}。您可以遵循BEM方法,只编写第一级选择器。
Scss:
.ads {
&__img {
width:100%;
}
&__h4 {
margin-top:45px;
margin-top: 45px;
font-weight: 600;
}
&__p {
margin-top: 5px;
font-weight: 500;
margin-bottom: 22px;
}
}Css输出:
.ads__img {
width: 100%;
}
.ads__h4 {
margin-top: 45px;
margin-top: 45px;
font-weight: 600;
}
.ads__p {
margin-top: 5px;
font-weight: 500;
margin-bottom: 22px;
}摘要
不要将所有的子元素嵌套到它的父元素中。编写更多可重用和上下文无关的代码。
https://stackoverflow.com/questions/39767090
复制相似问题