html - 背景颜色只填充 h2 元素而不是整个 div 容器

标签 html css

<分区>

我在下面有以下 div 和 h2 元素。我试图用蓝色填充整个 div,而不是像我期望的那样填充整个 container2 类,它只填充 h2 部分。为什么要这样做以及如何填充整个 container2 部分(在 h2 区域之外有一些边距和填充?

    h2 {
      color: white;
      font-size: 35px;
      font-weight: 500;
    }
    
    .container2 {
      text-align: center;
      font-family: Carnas-Light;
      background-color: #0f2c4d;
      margin-top: 40px;
      margin-bottom: 40px;
      padding-right: 15px;
      padding-left: 15px;
      width: 83.33333333%;
      margin-left: 8.33333333%;
      height: 100%;
    }
  <div class="container2">
                        <h2>WorkWave provides intuitive cloud-based field service & fleet management solutions that help organizations with a mobile workforce transform their business.</h2>
                </div>

最佳答案

只需将下一个样式代码添加到您的样式表中:

.container2 > h2 {
  background-color: #0f2c4d;
}

你的方法行不通,因为你只为父元素 container2 设置了 BG-color,而不是为 h2 使用继承和元素。

运行代码:

    h2 {
      color: white;
      font-size: 35px;
      font-weight: 500;
    }
    
    .container2 {
	    text-align: center;
	    font-family: Carnas-Light;
	    background-color: #0f2c4d;
	    padding-top: 40px;
	    padding-bottom: 40px;
	    padding-right: 15px;
	    padding-left: 15px;
	    width: 83.33333333%;
	    margin-left: 8.33333333%;
	    height: 100%;
    }

    .container2 > h2 {
      background-color: #0f2c4d;
    }
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Title</title>

  <style>


  </style>

</head>
<body>
	
	<div style="background-color: #0f2c4d;">
		<div class="container2">
            <h2>WorkWave provides intuitive cloud-based field service &amp; fleet management solutions that help organizations with a mobile workforce transform their business.</h2>
        </div>
    </div>

<script>


</script>

</body>
</html>

关于html - 背景颜色只填充 h2 元素而不是整个 div 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48734684/

上一篇:css - 创建一个可嵌套的 CSS 网格,在不丢失背景的情况下保持居中

下一篇:html - 垂直对齐容器内的输入框

相关文章:

jquery - 相同的函数将为每个独特的类使用不同的数组

html - 页脚元素未正确对齐

css - 让我的页脚贴在页面底部

html - 具体的高度和宽度,还要用padding/margin?

html - 在 CSS 中选择选中的元素

javascript - 使用 JQuery 和 CSS 在图像上叠加文本?

javascript - PHP 如果文件夹中存在图像则显示否则显示默认图像

html - 跨多个页面的 R 网络抓取

html - 难以使 h2 元素和左/右边框对齐

jquery - BootStrap 下拉类不需要吗?