我想实现一种越来越流行的设计-水平对齐两个50%宽度的div(.tile),但是两个div上的内容都限制为整体最大宽度(等于该网站其余部分的页面包装,例如1200px)。我让它们向左浮动以实现水平对齐,每种颜色都有对比色。想象一下横跨2个div的居中“覆盖”包装。以下代码有望说明我的设置:
的CSS
.full-width-row {
width: 100%; // 100% of entire page so child divs bg color will stretch
padding: 0;
margin: 0;
overflow: hidden;
height: auto;
position: relative;
}
.tile {
width: 50%;
float: left;
height: 100%;
margin-bottom: -99999px;
padding-bottom: 99999px // hack to fill height of parent
}
.tile-content {
padding: 5%;
}
.left {
background: #FFC15E;
}
.right {
background: #3E7F72;
}
的HTML
<div class="full-width-row">
<div class="tile left">
<div class="tile-content">
//CONTENT LEFT
</div>
</div>
<div class="tile right">
<div class="tile-content">
//CONTENT RIGHT
</div>
</div>
</div>
此处的父级(.full-width-row)是整个窗口的100%,因此2个子div的bg颜色将拉伸整个页面。我要在最大定义的宽度(等于1200px)内表现这些子项中的内容。有没有人建立过类似的布局或对如何实现这一目标有任何建议?
我猜右边的div永远不会有问题,因为它总是在1200px包装空间中,但是左手会在更大的屏幕上继续向左移动。
最佳答案
我不确定您想要什么,但是如果要使外部容器居中,则可以简单地将margin: 0 auto
应用于该容器。我在下面的代码段中执行了此操作,并添加了max-width: 500px
以使其在代码段窗口内立即可见(您当然可以将其设置为1200px)。
注意:仅当元素具有margin: 0 auto
设置时,才能使用position
居中(在您的示例中就是这种情况。)
html, body {
margin: 0;
}
.full-width-row {
width: 100%; // 100% of entire page so child divs bg color will stretch
padding: 0;
margin: 0;
overflow: hidden;
height: auto;
position: relative;
max-width: 500px;
margin: 0 auto;
}
.tile {
width: 50%;
float: left;
height: 100%;
margin-bottom: -99999px;
padding-bottom: 99999px;
background: #ddd;
}
.tile-content {
padding: 5%;
}
.left {
background: #FFC15E;
}
.right {
background: #3E7F72;
}
<div class="full-width-row">
<div class="tile left">
<div class="tile-content">
//CONTENT LEFT
</div>
</div>
<div class="tile right">
<div class="tile-content">
//CONTENT RIGHT
</div>
</div>
</div>
关于html - 包含宽度为总包装宽度(1200px)的50%宽水平水平div的内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44555306/