开发者

How can I make a div horizontally center itself in another div? [duplicate]

开发者 https://www.devze.com 2023-02-26 15:27 出处:网络
This question already has answers here: Closed 11 ye开发者_C百科ars ago. Possible Duplicate: How to center horizontally div inside parent div
This question already has answers here: Closed 11 ye开发者_C百科ars ago.

Possible Duplicate:

How to center horizontally div inside parent div

I have the following:

<div id="a">
<div id="b">abc</div>
</div>

My first div "a" is styled to be 100% of the screen width. I would like to make div "b" appear horizontally in the center. I know I can do this with tables but is there a way to do this with just div's and CSS?

Hope someone can help


You can set the margin-left and margin-right properties to auto. According to CSS2.1 § 10.3.3 you need to specify a width (other than auto) though:

#b {width: 300px; margin: 0 auto;}


you can do that by setting a fixed width to the child div such as and setting left/right margin auto. Like:

div#b{width:40px;margin:0 auto;}


The preferred way to do this would be to set the width of the child div and set the left and right margin to auto. Auto assigns equal amount to both left and right margins.

div#b { width: 100px; margin: 0 auto;}

If you are not sure about the width of the child, you can also assign text-align:center to the parent div. This might not be the best way but gets the job done.

div#a {text-align:center;}
0

精彩评论

暂无评论...
验证码 换一张
取 消