CSS 反包装元素填充的负边距

CSS Negative Margins to counter wrapper element padding

为什么分配给 .alert class 的负边距不起作用。我希望 .alert class 占据容器的整个宽度。我不想为所有元素分配单独的填充,因为只有 .alert 元素必须占据 .outer 容器的整个宽度。所有其他元素都应该有一个分配给外部容器的填充。

.outer{
  padding: 20px;
  background: red;
  margin: auto;
}

.alert{
  height: 20%;
  width: 100%;
  background: blue;
  margin: -20px -20px 0 -20px;
  color: white;
  padding: 10px;
}

.other{
  background: yellow;
  padding: 10px;
}
<div class="outer">
  <div class="alert">Hello! This is an alert</div>
  <div class="other">Content. Lorem ipsum blah blah blah</div>
  <div class="other">Content. Lorem ipsum blah blah blah</div>
  <div class="other">Content. Lorem ipsum blah blah blah</div>
  <div class="other">Content. Lorem ipsum blah blah blah</div>
  <div class="other">Content. Lorem ipsum blah blah blah</div>
</div>

width: 100% 使 .alert 的内容区域与其包含块一样宽,由 .outer 建立。您希望它通过负边距增长,但是 width 声明阻止了扩大。请改用默认 width: auto

.outer {
  padding: 20px;
  width: 80%;
  background: red;
  margin: auto;
}
.alert {
  height: 20%;
  background: blue;
  margin: -20px -20px 0 -20px;
  color: white;
  padding: 10px;
}
.other {
  background: yellow;
  padding: 10px;
}
<div class="outer">
  <div class="alert">Hello!</div>
  <div class="other">Content</div>
  <div class="other">Content</div>
  <div class="other">Content</div>
  <div class="other">Content</div>
  <div class="other">Content</div>
</div>

替代width:100%

如其他答案所述,Width:auto 可能是最佳解决方案。但是如果你想保留 Width:100% 你可以:

  • alert 的宽度设置为 100%
  • alert 和父 outer
  • 设置相同的填充
  • 添加一个等同于填充的元格边距以向左移动alert

.outer{
  padding: 20px;
  background: red;
  margin: auto;
}

.alert{
  height: 20%;
  width: 100%;
  background: blue;
  margin-left: -20px;
  margin-top:-20px;
  color: white;
  padding: 20px;
}

.other{
  background: yellow;
  padding: 10px;
}
<div class="outer">
  <div class="alert">Hello! This is an alert</div>
  <div class="other">Content. Lorem ipsum blah blah blah</div>
  <div class="other">Content. Lorem ipsum blah blah blah</div>
  <div class="other">Content. Lorem ipsum blah blah blah</div>
  <div class="other">Content. Lorem ipsum blah blah blah</div>
  <div class="other">Content. Lorem ipsum blah blah blah</div>
</div>