简体   繁体   中英

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.

The parent div should have a fixed height (150px) and fluid width (80%).

The child div should have a fluid height (expands with content) and fluid width (always 100%).

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.

Here's what I have right now:

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)

Notice that display:table can be used as a fall back for older browser

DEMO


Basic update to your 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:

Demo Fiddle

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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