0

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.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • Are you after something like [this example](http://jsbin.com/pulora/1/edit?html,css,output) ? – misterManSam Oct 29 '14 at 04:00
  • Hmmm, something like that (centering just foo). Amazed, not working with my site... – Bhojendra Rauniyar Oct 29 '14 at 04:15
  • "bar" is going to come along for the ride because it is a child of `#foo`. Its the same as this: `
    bar
    foo
    `. To break it out, you would have to [do something like this example](http://jsbin.com/pulora/2/edit)
    – misterManSam Oct 29 '14 at 04:39
  • possible duplicate of [How to vertically center content with variable height within a div?](http://stackoverflow.com/questions/59309/how-to-vertically-center-content-with-variable-height-within-a-div) – user Dec 16 '14 at 11:32

2 Answers2

1

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

JimmyRare
  • 3,958
  • 2
  • 20
  • 23
0

Try this:

#foo {
height: auto;
margin:auto;
position:absolute;
top:50%;
}
Duetschpire
  • 167
  • 11
  • the updated answer should place the #foo in the middle of the screen, the problem would be is that if #foo is 300px, it will be 50% from the top of the screen but wouldn't be right in the middle, unless you have #foo {top: calc(50% - 150px);} /* half the height of #foo */ – Duetschpire Oct 29 '14 at 04:00