aftard
aftard

Reputation: 41

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;
}

Upvotes: 1

Views: 13098

Answers (3)

Sandet
Sandet

Reputation: 27

This works for me:

.Box {
   background-color: lightgrey;
   width: 400px;
   border: 25px solid grey;
   padding: 25px;
   margin: 25px;
   align-content:center;
   position: fixed;
   top: 50%;
   left: 50%;
   margin-top: -50px;
   margin-left: -100px;
}

Upvotes: 0

Kevin Ji
Kevin Ji

Reputation: 10489

Try the following CSS:

#box
{
    margin: 0 auto;
    width: 100px; /* Or some other width */
}

Upvotes: 4

Jonathan Nicol
Jonathan Nicol

Reputation: 3298

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

Upvotes: 2

Related Questions