垂直对齐流体div中的流体div [英] Vertical align fluid div within another fluid div
问题描述
我已经看到很多解决方案,如果孩子div有固定的宽度,但不是,如果它是流动的。
I've seen plenty of solutions if the child div has a fixed width, but not if it is fluid.
父div应该有一个固定的高度
The parent div should have a fixed height (150px) and fluid width (80%).
子div应具有流体高度(随内容扩展)和流体宽度(始终为100%)。
The child div should have a fluid height (expands with content) and fluid width (always 100%).
我想让子div在父div中垂直对齐。
I want to get the child div to vertically align within the parent div. All content within the child div should also be horizontally centered.
以下是我现在的状态:
<div class="s1">
<div class="centereddiv">This green div should be vertically centered.</div>
</div>
-
body, html {
height: 100%;
margin: 0;
}
.s1 {
width:100%;
height: 150px;
display: block;
background-color: red;
float: left;
}
.centereddiv {
color: black;
text-align: center;
background-color: green;
}
推荐答案
可以使用 display:table
,但是您还需要稍微调整HTML,并添加一个额外的父级:
Likely the most flexible implementation would be to leverage display:table
, however you will also need to adapt your HTML slightly and add an additional parent:
<div class="table">
<div class="cell">
<div class="childcentereddiv">This green div should be vertically centered.</div>
</div>
</div>
CSS
body, html {
height: 100%;
margin: 0;
width:100%;
padding:0;
}
.table {
height: 150px;
background-color: red;
display:table;
width:80%;
}
.cell {
display:table-cell;
vertical-align:middle;
}
.childcentereddiv {
color: black;
text-align: center;
background-color: green;
}
这篇关于垂直对齐流体div中的流体div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!