背景颜色不随媒体查询拉伸

Background color not stretching with media query

我想了解为什么 "row" 元素的背景颜色在平板电脑上无法拉伸。在平板电脑上它只出现在 "center" 元素中,而在桌面上它也适用于 "left" 和 "right" divs。在代码中,我将 "right" div 放在 "center" div 之前,因为我想将 "right" div 对齐到 "left" div 在 mobile/tablets.

Edit2: 我刚刚意识到真正的问题是 center [=42= 中 h3 标签的背景颜色] 应用于 leftright div。虽然,我没有找到任何解决方案,也没有找到发生这种情况的原因。

编辑:我刚刚注意到,如果我在 center 元素的媒体查询中使用 clear:both; 而不是 float:none;,它就会起作用。为什么?

.row {
  background-color: #5c5c5c;
}
.row h3{
  background-color: #fff;
}
.left {
  width: 25%;
  float: left;
  color: #fff;
  padding: 0 10px 0 10px;
}
.right {
  width: 25%;
  float: right;
  color: #fff;
  padding: 0 10px 0 10px;
}
.center {
  width: 50%;
  float: left;
  border-left: 2px solid #eaeaea;
  border-right: 2px solid #eaeaea;
}
.clear {
  clear: both;
}
@media (max-width: 1023px) and (min-width: 768px) {
  .left {
    float: left;
    width: 50%;
  }
  .right {
    float: left;
    width: 50%;
  }
  .center {
    float: none;
    width: 100%;
  }
}
<div class="row">
  <div class="left">
    content
  </div>
  <div class="right">
    content
  </div>
  <div class="center">
    <h3>content</h3>
  </div>
  <div class="clear"></div>
</div>

有几个问题需要解决:

(1) 您正在为网格使用 width + padding + border,最好将应用 box-sizing: border-box 设置为它们,或者仅对所有应用设置,例如

* {
  box-sizing: border-box;
}

这样任何填充和边框都将计算为宽度的一部分。

(2) 您在所有三个左、右和中心 div 下方设置了 <div class="clear"></div>,这有效。但是,在您的媒体查询中,中心不再浮动,因此您必须在左右 div 之后立即清除浮动。您可以只添加 clear: both;.

@media (max-width: 1023px) and (min-width: 768px) {
  .center {
    ...
    clear: both;
  }
}

jsFiddle

旁注,<h3> 标签有默认边距,因此白色背景可能不会一直扩展到顶部和底部,您可以使用 margin: 0; 重置它并使用 padding 而不是如果你确实需要间距。