【问题标题】:Background color in div element not showing [duplicate]div元素中的背景颜色不显示[重复]
【发布时间】:2021-04-14 09:19:55
【问题描述】:

我正在学习这门名为 HTML、CSS 和 Javascript 的面向 Web 开发人员的课程。我在讲浮动元素的讲座中,我的问题是当我将属性“float”和“margin-right”添加到元素 p 选择器时,div 的背景消失了。有人可以帮帮我吗?

div {
  background-color: blue;
}

p {
  width: 50px;
  height: 50px;
  border: 1px solid black;
  float: left;
  margin-right: 10px;
}

#p1 {
  background-color: #A52A2A;
}

#p2 {
  background-color: #DEB887;
}

#p3 {
  background-color: #5F9EA0;
}

#p4 {
  background-color: #FF7F50;
}

section {
  clear: left;
}
<div>
  <p id="p1"></p>
  <p id="p2"></p>
  <p id="p3"></p>
  <p id="p4"></p>
</div>
<section>This is regular content continuing after the paragraph boxes</section>

【问题讨论】:

标签: html css css-selectors


【解决方案1】:

因为您使用的是float,您需要清除它,因为它会从文档流中删除。这个清除过程也称为Clearfix

你可以这样做:

div:after {
  content: "";
  display: table;
  clear: both;
}

div {
  background-color: blue;
}

div:after {
  content: "";
  display: table;
  clear: both;
}

p {
  width: 50px;
  height: 50px;
  border: 1px solid black;
  float: left;
  margin-right: 10px;
}

#p1 {
  background-color: #A52A2A;
}

#p2 {
  background-color: #DEB887;
}

#p3 {
  background-color: #5F9EA0;
}

#p4 {
  background-color: #FF7F50;
}

section {
  clear: both;
}
<div>
  <p id="p1"></p>
  <p id="p2"></p>
  <p id="p3"></p>
  <p id="p4"></p>
</div>
<section>This is regular content continuing after the paragraph boxes</section>

你现在不应该使用floats。使用flexboxgrid 等现代技术。

一些有用的资源:

【讨论】:

  • 非常感谢!!它似乎解决了这个问题。我会检查链接,猜想我所学的课程有点过时了......你太好了,再次感谢你:3
  • @Lunazul8 阅读所有这些链接并不重要。 . .仅供参考。 . .能不能把课程的网址分享给我看看!
  • 但是第一个链接解决了我的问题,我添加了属性溢出:auto;到 div 并且它起作用了:3...这是课程的链接:coursera.org/learn/html-css-javascript-for-web-developers/…
  • @Lunazul8 这对我来说似乎太老了。 . .您应该更喜欢一次更好的课程,您想要高级课程还是免费课程!
  • 我买不起高级版,所以免费版对我来说是更好的选择
【解决方案2】:

float 属性从文档流中删除元素。由于div 包含p 浮动元素并且没有设置height,因此高度为0。为div 设置高度。

【讨论】:

  • 当我为背景设置任何高度时,部分元素的内容会在背景之上,将其分割:c
【解决方案3】:

float 属性的行为类似于 position:absolute

即使&lt;p&gt;&lt;div&gt; 中,此属性也会使其“弹出”&lt;div&gt;,移除其自动高度和宽度,从而使&lt;div&gt; 高度为0px,宽度为0px ,这样你就看不到了

解决它的一种方法是为您的&lt;div&gt; 设置高度和宽度

【讨论】:

  • 我试过了,但是 section 元素介于两者之间,划分了背景:c... 还是谢谢你
猜你喜欢
  • 2010-12-19
  • 2014-02-26
  • 2019-10-31
  • 2021-10-19
  • 1970-01-01
  • 1970-01-01
  • 2011-07-17
  • 2012-04-02
  • 1970-01-01
相关资源
最近更新 更多