这将成为页面的页脚。 我有一个带有背景颜色的 div 和 2 个与 div 具有相同背景颜色的段落。一段向左浮动,另一段向右浮动。我唯一看到背景颜色的地方就在段落文本的正后方。
虽然我确实找到了解决表格的方法,但我想知道为什么它会以这种方式出现。为什么当 Inspect 元素另有说明时 div 似乎没有背景颜色?
代码
<!DOCTYPE html>
<html>
<head>
<style>
div.holder{
position:absolute;
margin-left:auto;
margin-right:auto;
width:65%;
}
div.footer{
position:relative;
width: 100%;
background-color: #00A2E8;
}
div.footer p{
background-color: #00A2E8;
overflow: hidden
}
</style>
</head>
<body >
<div class="holder">
<div class="footer" >
<p style="float:left; ">
gdfgdfgdfgdffgdf</br>
dfgdfgdfgd </br>
dgdfgdfg ,</br>
dfgdfgdf </br>
gdfgdfgf </br>
</br>
</p>
<p style="float:right;">
<span>Phone:</span> 555555555</br>
<span>FAX:</span> 55555555555</br>
<span>Email:</span>info@example.com</br>
<span>Website:</span>example.com</br>
</div>
</div>
</body>
</html>
最佳答案
您正在使用 position: absolute;
至 div.holder
如果您在 div.footer
上使用该声明(而不是relative
定位)然后background-color: #00A2E8;
你的div.footer
将工作。
div.holder {
position:absolute;
margin-left:auto;
margin-right:auto;
width:65%;
}
div.footer {
position:absolute;
width: 100%;
background-color: #00A2E8;
}
div.footer p {
background-color: #00A2E8;
overflow: hidden;
}
这是因为它建立了一个新的 block 格式化上下文。
绝对定位元素,即位置为 absolute
的元素或 fixed
建立一个新的 block formatting context (简称:BFC)
这记录在 spec 中:
Floats, absolutely positioned elements, block containers (such as inline-blocks, table-cells, and table-captions) that are not block boxes, and block boxes with 'overflow' other than 'visible' (except when that value has been propagated to the viewport) establish new block formatting contexts for their contents.
block 格式化上下文是:
it is a part of a visual CSS rendering of a Web page. It is the region in which the layout of block boxes occurs and in which floats interact with each other.
- Mozilla MDN
规范 states :
In a block formatting context, each box's left outer edge touches the left edge of the containing block (for right-to-left formatting, right edges touch). This is true even in the presence of floats
因此,创建 BFC 的容器将包含其中的所有 float 元素。
此外, MDN 澄清了这一点:
A block formatting context contains everything inside of the element creating it that is not also inside a descendant element that creates a new block formatting context.
你应该使用 CSS clear
指定元素是可以紧挨着它前面的 float 元素还是必须向下移动(清除)到它们下面的属性。
当您将 CSS clear 属性应用于 float 元素时,它会将元素的外边距移动到所有相关 float 的外边距边缘下方。通过 Mozilla MDN
您可以使用额外的 <div style="clear: both;"></div>
就在您关闭之前div.footer
标签。
关于html - div背景不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25753292/