这将成为页面的页脚.
我有一个背景颜色的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上使用那个声明(而不是相对定位)那么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 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.
块格式化上下文是:
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.
– 07003
规范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的容器将包含其中的所有浮动元素.
此外,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属性来指定元素是否可以在其前面的浮动元素旁边,或者必须在它们下面向下移动(清除).
将CSS clear属性应用于浮动元素时,它会将元素的边缘移动到所有相关浮点的边缘下方.到Mozilla MDN
您可以使用额外的< div style =“clear:both;”>< / div>就在你关闭div.footer标签之前.