How can I center a box in CSS?

11,111

Solution 1

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%).

Solution 2

Try the following CSS:

#box
{
    margin: 0 auto;
    width: 100px; /* Or some other width */
}
Share:
11,111
aftard
Author by

aftard

Updated on July 01, 2022

Comments

  • aftard
    aftard almost 2 years

    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;
    }
    
    • kevinji
      kevinji about 13 years
      Wait, why are you centering the box, if it's display: none?
    • aftard
      aftard about 13 years
      when it appears i want to be centered
    • kei
      kei about 13 years
      Take out position and left, then add margin:auto;
    • aftard
      aftard about 13 years
      @mc10 this is the box that appears like that of google auto suggest but this is coded in php, mysql, and jquary. Now does it make sense?
  • Shad
    Shad about 13 years
    just make sure to give it a width, or centered is meaningless
  • kevinji
    kevinji about 13 years
    @Shad He already declared width : 30%;, so it should be fine.
  • Shad
    Shad about 13 years
    P does that mean you presume he imports his entire previous rule?
  • kevinji
    kevinji about 13 years
    @Shad Yes; I only mean to add my rule to his.
  • Shad
    Shad about 13 years
    sorry, to clarify, your rule tacked on to his, won't do anything useful (OP has position:absolute), and your rule alone also won't do anything useful (no width)