Search code examples
cssscreenresolution

How can I center a box in CSS?


I would like to know how can i center this box?

HTML Code:

<div id="box"></div>

CSS Code:

#box
{
  width : 30%;
  height : auto;
  overflow : auto ;
  border : 1px solid #C5C5C5;
  background : #F8F8F8;
  position : absolute;
  left : 33.6%;
  border-top : none;
  text-align : left;
  display : none;
}

Solution

  • Since #box is absolutely positioned, you would center it like so:

    #box {
        left: 50%; /* centers #box in its containing element */
        margin-left: -15%; /* half the element's width (30%) */
    }
    

    Those properties are in addition to the ones you've set already.

    The idea is to position #box's left edge in the center of its containing element (left: 50%), then move #box left by half its own width by giving it a negative margin (margin-left: -15%).