为什么我的媒体查询会将元素从容器中取出?

问题描述

您好社区:我现在正在学习GridSystems。我根据屏幕尺寸进行了2次媒体查询:第一个是768像素,第二个是480像素。但是当我调整屏幕尺寸时,元素从它们的容器中出来。为什么?我已经应用了clearfix hack。 我希望这些元素不要来自它们的容器元素。(不一定是.container,而是每个容器元素。)

O(3^(n/3))
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%}
}

解决方法

事物的结合:

  • 我建议不要将父.row元素的高度设置为明确
  • 但是要在子元素.col上设置它-如果需要的话-最好不要设置它,而是让元素的自然流动由内而外填充
  • 在行类上添加伪clearfix

我已经在css块编辑器中对此进行了注释,请注意这是否清除了

有一些引导程序和其他一些框架可以自动为您执行此操作,但是最好走低路并了解中心下的工作方式-欢呼

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>

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...