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 */
}
Author by
aftard
Updated on July 01, 2022Comments
-
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 about 13 yearsWait, why are you centering the box, if it's
display: none
? -
aftard about 13 yearswhen it appears i want to be centered
-
kei about 13 yearsTake out
position
andleft
, then addmargin:auto;
-
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 about 13 yearsjust make sure to give it a width, or
centered
is meaningless -
kevinji about 13 years@Shad He already declared
width : 30%;
, so it should be fine. -
Shad about 13 yearsP does that mean you presume he imports his entire previous rule?
-
kevinji about 13 years@Shad Yes; I only mean to add my rule to his.
-
Shad about 13 yearssorry, 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)