首页 > 解决方案 > 具有预先确定宽度的 Div 内具有背景颜色的 Div

问题描述

我觉得我应该能够解决这个问题,但我真的不能......

我基本上有一个包含另一组 div/元素的 div。我希望此容器中的第一个 div 具有背景颜色,以有效地为父 div 提供彩色顶栏/部分。我能得到的最接近的是使用 display: flex; 给它全高度着色,但我无法按照我想要的方式得到它。任何帮助表示赞赏。

.container {
  border: 1px solid grey;
  border-radius: 4px;
  padding: 0px 10px 10px 10px;
}

.content {
  height: 400px;
}

.sp-h3 {
  display: flex;
  background-color: #008ed0;
  color: white;
}

* {
  box-sizing: border-box;
}

.container::before,
.container::after {
  content: "";
  clear: both;
}
<div class="container">
  <div class="sp-h3">
    <h3>Bob McBob</h3>
  </div>
  <div class="content">
    <p>Just for something</P>
    <ul>
      <li>The number 1</li>
      <li>The number 2</li>
      <li>The number 3</li>
      <li>The number 4</li>
    </ul>
  </div>
</div>

标签: htmlcss

解决方案


您可以设置padding为子元素,而不是将其设置为整个.container.

.container {
  border: 1px solid grey;
  border-radius: 4px;
  
}

.content {
  height: 400px;
  padding: 0px 10px 10px 10px;
}

.sp-h3 {
  display: flex;
  background-color: #008ed0;
  color: white;
  padding: 0px 10px 10px 10px;
}

* {
  box-sizing: border-box;
}

.container::before,
.container::after {
  content: "";
  clear: both;
}
<div class="container">
  <div class="sp-h3">
    <h3>Bob McBob</h3>
  </div>
  <div class="content">
    <p>Just for something</P>
    <ul>
      <li>The number 1</li>
      <li>The number 2</li>
      <li>The number 3</li>
      <li>The number 4</li>
    </ul>
  </div>
</div>


推荐阅读