简体   繁体   中英

vertically centering the element for auto height div

html:

<div id="main">
    <div id="foo">foo</div>
</div>

css:

html,body{
    height: 100%;
}
#main{
    height: 100%;
}
#foo{
    height: auto;
    /* height: 100%; I cannot use height 100% or fixed height for this element*/
}
#foo:before{
    content: "bar";
/*I want to use the height in percentage which won't work but work with px*/
    height: 100%;
    display: block;/* or inline-block*/
}

demo

I cannot use flexbox css for some reason. And I also tried with transform css technique and various techniques such as table but even couldn't get vertical center.

I cannot change the markup and please if possible without touching the css for #main would be great for me.

You can center an element vertically within it's container using this technique:

#foo{
    position: absolute;
    top: 50%; // move down 50% of parent
    transform: translateY(-50%); // move back up 50% of own height
}

Set position: relative; on the #main container to make #foo relate to it.

Demo

Try this:

#foo {
height: auto;
margin:auto;
position:absolute;
top:50%;
}

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