Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center a percentage based div within a fullscreen div

I know that margin-top in percentages are relative to the width... That's why, I can't always vertically and horizontally center a div that is 50% height, and 50% width of the full screen.

http://jsfiddle.net/8BJ94/

When you resize, the margin-top is relative to the width

CSS

#mini {
   height : 50%;
   width : 50%;
   background-color : #FFFFFF;
   margin-top : 25%;
   margin-left : 25%;
}
like image 224
Damien Avatar asked Nov 15 '13 23:11

Damien


2 Answers

Demo

http://jsfiddle.net/8BJ94/1/

Code

#hello {
    position : absolute;
    width : 100%;
    height : 100%;
    background-color : #123456;
    text-align: center;
}
#hello:before {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}
#mini {
    height : 50%;
    width : 50%;
    background-color : #FFFFFF;
    display: inline-block;
    vertical-align: middle;
}

Based on http://css-tricks.com/centering-in-the-unknown/

How does it work?

  • Horizontal centering (easy):

    #hello {
        text-align: center;
    }
    #mini {
        display: inline-block;
    }
    
  • Vertical centering:

    1. Make line's height to be 100% height with a ghost element:

      #hello:before {
          content: '';
          display: inline-block;
          height: 100%;
          vertical-align: middle;
      }
      
    2. Center #mini vertically (relatively to that line) with vertical-align:

      #mini {
          display: inline-block;
          vertical-align: middle;
      }
      

Browser support

Essentially everything and IE 8+.

You can support IE7 too if you use a real element as a ghost, instead of a :before pseudo element. But it isn't semantically correct.

like image 55
Oriol Avatar answered Oct 12 '22 03:10

Oriol


Here is the best approach: (live example). It is supported in all modern browsers. Reference.

Set the html/body elements to height:100% and width:100%.

Then set the display of the body, or the parent element to table.

Finally, use display:table-cell, and vertical-align:middle on the child element.

That will take care of the vertical alignment.

In order to center horizontally, set margin:0px auto on the child element.

In certain cases where the width of the child isn't defined or is dynamically generated, you can also use text-align:center assuming it is an inline element.

HTML

<div id="parent">
    <div id="child"></div>
</div>

CSS

html, body {
    height:100%;
    width:100%;
    margin:0px;
}
body {
    display:table;
}

#parent {
    display:table-cell;
    vertical-align:middle;
    background:#123456;
}
#child {
    height:50%;
    width:50%;
    background:white;
    margin:0px auto;
}
like image 35
Josh Crozier Avatar answered Oct 12 '22 02:10

Josh Crozier