2017-10-28 41 views
1

我将如何在@media中设置所有子元素而不添加所有类。@media设置所有包装子元素

.wrapper> *似乎不起作用,不知道为什么。

这是一个简单的例子:

.wrapper { 
 
    width: 100%; 
 
} 
 

 
.wrapper .left { 
 
    background-color: #2196F3; 
 
    float: left; 
 
    width: 50% !important; 
 
} 
 

 
.wrapper .right { 
 
    background-color: #4CAF50; 
 
    float: right; 
 
    text-align: right; 
 
    width: 50% !important; 
 
} 
 

 
@media (max-width:400px) { 
 
    .wrapper>* { 
 
    width: 100%; 
 
    text-align: center; 
 
    }
<div class="wrapper"> 
 
    <div class="left"> 
 
    Left Menu<br><br><br><br> 
 
    </div> 
 

 
    <div class="right"> 
 
    Right Content<br><br><br><br> 
 
    </div> 
 
</div> 
 

 

 
<p>Resize the browser window.</p> 
 

 
<p>Make sure you reach the breakpoint at 400px when resizing this frame.</p>

回答

0

试试这个:

.wrapper { 
 
    width: 100%; 
 
} 
 

 
.wrapper .left { 
 
    background-color: #2196F3; 
 
    float: left; 
 
    width: 50%; 
 
} 
 

 
.wrapper .right { 
 
    background-color: #4CAF50; 
 
    float: right; 
 
    text-align: right; 
 
    width: 50%; 
 
} 
 

 
@media (max-width: 400px) { 
 
    .wrapper .left, 
 
    .wrapper .right { 
 
    width: 100%; 
 
    } 
 
}
<div class="wrapper"> 
 
    <div class="left"> 
 
    Left Menu<br><br><br><br> 
 
    </div> 
 

 
    <div class="right"> 
 
    Right Content<br><br><br><br> 
 
    </div> 
 
</div> 
 

 

 
<p>Resize the browser window.</p> 
 

 
<p>Make sure you reach the breakpoint at 400px when resizing this frame.</p>

摆脱!important您的div并确保在@media部分规则具有specificity不弱比在主要部分应用的要多。

此外,使用通用选择器(*)不是最好的主意,因为它没有特殊的价值。因此,.wrapper > *具有(0,0,1,0)特异性,而之前定义的.wrapper .left.wrapper .right具有比(0,0,1,0)更强的(0,0,2,0),因此它们获胜。

虽然在这种情况下它不是那么重要,但样式从右向左被解析。所以,在右边添加“*”可能会让浏览器更难以解析和应用样式。

另外!important使整个风格更难以保持和理解,所以它是安全的,除非它是完全必要的。

0

你的问题是与CSS的特殊性,您使用!important这是压倒一切的媒体查询的CSS,而不是你需要添加重要在媒体查询中:

为什么你需要!在媒体查询中很重要?

.wrapper .right.wrapper > *更具特异性,所以您需要添加重要的内容才能使用此选择器应用媒体查询中的样式。

.wrapper { 
 
    width: 100%; 
 
} 
 

 
.wrapper .left { 
 
    background-color: #2196F3; 
 
    float: left; 
 
    width: 50%; 
 
} 
 

 
.wrapper .right { 
 
    background-color: #4CAF50; 
 
    float: right; 
 
    text-align: right; 
 
    width: 50%; 
 
} 
 

 
@media (max-width:800px) { 
 
    .wrapper > * { 
 
    width: 100%!important; 
 
    text-align: center!important; 
 
    } 
 
}
<div class="wrapper"> 
 
    <div class="left"> 
 
    Left Menu<br><br><br><br> 
 
    </div> 
 

 
    <div class="right"> 
 
    Right Content<br><br><br><br> 
 
    </div> 
 
</div> 
 

 

 
<p>Resize the browser window.</p> 
 

 
<p>Make sure you reach the breakpoint at 400px when resizing this frame.</p>

相关问题