假设我有一个包含子 div 的 div。容器 div 设置为 margin: 0
auto,因此当宽度增加时,div 会在两侧扩展。如果这个容器内的 div 也被设置为 margin: 0
auto,有没有办法让这个 div 扩展到它的容器 div 之外,并且向右和向左的距离相等?
下面的例子表明,当 .background 的宽度增加到超过容器的宽度时,它的大小只会从右边增加,而不是从两侧增加。
CSS 和 HTML:
.container {
width: 600px;
background-color: lightgreen;
margin: 0 auto;
}
.background {
width: 300px;
margin: 0 auto;
background-color: blue;
}
.content {
width: 200px;
background-color: lightblue;
margin: 0 auto;
}
<div class = "container">
<div class = "background">
<div class = "content">
content
</div>
</div>
</div>
这都是为了让横幅图形背景图像跨越页面的正文宽度,但仍然让页面内部的内容保持不变。
最佳答案
假设您希望 background
div 在每一侧突出 50px。你可以在你的 CSS 中这样做:
.background {
margin: 0 -50px 0 -50px;
background-color: #00F;
}
一个完整的例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
.container {
width: 500px;
background-color: lightgreen;
margin: 0 auto;
height: 400px; /* for illustration */
}
.background {
margin: 0 -50px;
background-color: blue;
}
.content {
width: 200px;
background-color: lightblue;
margin: 0 auto;
}
</style>
</head>
<body>
<div class = "container">
<div class = "background">
<div class = "content">
content
</div>
</div>
</div>
</body>
</html>
关于html - 在容器 div 之外平均扩展子 div,两侧边距为 : 0 auto,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16421808/