我正在尝试实现某种流畅的布局,其中每个 DIV 的内容在垂直和水平方向上居中。但是,我的中间行(A、B、C)一直存在垂直和/或水平对齐问题。
目标是让它像这样工作:
Note: If there's a way I can have the option to set the Mobile layout's "C" area fluid as well (without having to change the HTML, just the CSS, so that I can test which option works best), that'd be a bonus!
这是 HTML 的片段:
<div class="page">
<div class="col col-top">top</div>
<div class="col col-mid">
<div class="col col-left">
<div class="centerBox"><div class='debugBox'></div></div>
</div>
<div class="col col-center">
<div class="centerBox"><div class='debugBox'></div></div>
</div>
<div class="col col-right">
<div class="centerBox"><div class='debugBox'></div></div>
</div>
</div>
<div class="col col-bottom">bottom</div>
</div>
我不确定带有“centerBox”类的“包装”DIV 是否真的有必要(它们被设置为 display: table-cell
而每个 col 类被设置为 display: table
以表现像表格,但这会导致将这些区域放置为 position: absolute
和 % 值的问题它们的左/右/上/下属性。
例如,如果“C”区域设置为display: table
,会发生这种情况:
如果我将“C”区域更改为 display: block;
,那么它会填满整个中心区域,但是......
...水平和垂直对齐方式在其中中断。
使用“Ghost”DIV 元素(如 css-tricks article 中所讨论,Chris Coyier 的“Centering in the Unknown”)是否会更好地获得正确对齐?
最佳答案
好的,这个解决方案没有框架,使用 flexbox 的纯 CSS。只要布局是水平的,C 就有固定的宽度。移动时,C占据整个宽度,高度可变。
header,
footer {
padding: 10px;
background-color: lightblue;
}
main {
display: flex;
flex-direction: row;
}
main > div {
padding: 10px;
background-color: tomato;
flex-grow: 1;
min-height: 40px;
display: flex;
align-items: center;
}
main > div:nth-child(2) {
background-color: olive;
}
.fixed {
width: 400px;
}
@media (max-width: 768px) {
main {
flex-direction: column;
}
.fixed {
width: auto;
}
}
<header>Top</header>
<main>
<div>A</div>
<div class="fixed">C</div>
<div>B</div>
</main>
<footer>Bottom</footer>
这里是笔(拖动边框看移动布局): Codepen
关于html - 如何在媒体查询设置的流体布局中垂直和水平居中子元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33875537/