社区您好:我现在正在学习GridSystems。我根据屏幕大小进行了两次媒体查询:第一次是768px,第二次是480px。但当我调整屏幕大小时,元素就从它们的容器中出来了。为什么?我已经应用了clearfix破解。我希望元素不要从它们的容器元素中出来。(不一定。容器,但每个容器元素。(
html,body{
box-sizing:border-box;
margin:0;
}
.container{
width:95%;
margin-left:auto;
margin-right:auto;
background-color:yellow;
}
.container::after{
content:"";
clear:both;
display:block;
}
.row{
box-sizing:border-box;
height:50px;
border:5px solid orange;
width:auto;
}
.col{
float:left;
box-sizing:border-box;
height:100%;
border:5px solid red;
width:auto;
}
.col-1{width:16.6666%;}
.col-2{width:33.3333%;}
.col-3{width:50%;}
.col-4{width:100%;}
/*Wichtige Viewports
>1200+px:Desktop
768px:Tablet Hochformat;
480px:Handy Querformat
*/
@media(max-width:768px){
.col-1{width:50%}
.col-2{width:50%}
}
@media(max-width:480px){
.col-1{width:100%}
.col-2{width:100%}
.col-3{width:100%}
}
<div class="container">
<div class="row">
<div class="col col-1"></div>
<div class="col col-1"></div>
<div class="col col-1"></div>
<div class="col col-1"></div>
<div class="col col-1"></div>
<div class="col col-1"></div>
</div>
<div class="row">
<div class="col col-2"></div>
<div class="col col-2"></div>
<div class="col col-2"></div>
</div>
<div class="row">
<div class="col col-3"></div>
<div class="col col-3"></div>
</div>
<div class="row">
<div class="col col-4"></div>
</div>
</div>
两件事:
- 我建议不要显式设置父
.row
元素的高度 - 但是ruther将其设置在子元素
.col
上——如果需要的话——最好不要设置它,而是让元素的自然流动由内而外填充 - 在行类上添加伪clearfix
我已经在css块编辑器中评论了这一点,所以看看这是否会清除你的斗鱼
有一些像bootstrap和其他一些框架可以为你自动完成这项工作,但最好走低路,学习如何在集线器下工作-欢呼
html,
body {
box-sizing: border-box;
margin: 0;
font-size: 16px;
}
.container {
width: 95%;
margin-left: auto;
margin-right: auto;
background-color: yellow;
}
.row {
box-sizing: border-box;
/* height: 50px;
I'd suggest to not have explicit height set on parent
*/
border: 5px solid orange;
width: auto;
}
/* set row's after pseudo to clear floats of child elems - short clearfix */
.row:after{
content: '';
clear: both;
display: table;
}
.col {
float: left;
box-sizing: border-box;
height: 2em; /* but would suggest to set height of child elements - .col's */
border: 5px solid red;
width: auto;
}
.col-1 {
width: 16.6666%;
}
.col-2 {
width: 33.3333%;
}
.col-3 {
width: 50%;
}
.col-4 {
width: 100%;
}
/*Wichtige Viewports
>1200+px:Desktop
768px:Tablet Hochformat;
480px:Handy Querformat
*/
@media(max-width:768px) {
.col-1 {
width: 50%
}
.col-2 {
width: 50%
}
}
@media(max-width:480px) {
.col-1 {
width: 100%
}
.col-2 {
width: 100%
}
.col-3 {
width: 100%
}
}
<div class="container">
<div class="row">
<div class="col col-1"></div>
<div class="col col-1"></div>
<div class="col col-1"></div>
<div class="col col-1"></div>
<div class="col col-1"></div>
<div class="col col-1"></div>
</div>
<div class="row">
<div class="col col-2"></div>
<div class="col col-2"></div>
<div class="col col-2"></div>
</div>
<div class="row">
<div class="col col-3"></div>
<div class="col col-3"></div>
</div>
<div class="row">
<div class="col col-4"></div>
</div>
</div>