简体   繁体   English

在另一个流体div中垂直对齐流体div

[英]Vertical align fluid div within another fluid 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的高度应固定为150px,流体宽度应为80%。

The child div should have a fluid height (expands with content) and fluid width (always 100%). 子div的流体高度(随内容扩展)和流体宽度(始终为100%)。

I want to get the child div to vertically align within the parent div. 我想让子div在父div内垂直对齐。 All content within the child div should also be horizontally centered. 子div中的所有内容也应水平居中。

Here's what I have right now: 这是我现在所拥有的:

http://jsfiddle.net/6986r/ http://jsfiddle.net/6986r/

<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;
}

If you do not mind older browser, you may use the display:flex property (aside the table property already proposed by @SW4) 如果您不介意使用旧版浏览器,则可以使用display:flex属性(除了@ SW4已经建议的table属性)

Notice that display:table can be used as a fall back for older browser 请注意, display:table可用作旧版浏览器的后备

DEMO 演示


Basic update to your CSS: CSS的基本更新:

.parent {
    display:flex;
}
.childcentereddiv {
    margin:auto;
}

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: 最灵活的实现可能是利用display:table ,但是您还需要稍微调整HTML并添加一个附加的父级:

Demo Fiddle 演示小提琴

<div class="table">
    <div class="cell">
        <div class="childcentereddiv">This green div should be vertically centered.</div>
    </div>
</div>

CSS 的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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM