deltanovember
deltanovember

Reputation: 44051

How do I center a box and its contents in CSS?

I have had look at some of the other answers but could not get them working for my particular case. I have simplified and included the entire block of code below. Basically it just displays text in a blue box. I would like to know how to center the box.

<!DOCTYPE html>

<html>
<head>
    <style type="text/css"><!--
#content {
width:500px;
padding: 10px 10px 10px;
background-color: #D1ECFF;
position: relative;
border-radius: 10px;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
}
--></style>
</head>
<body>

<div id="content">

    <h2>Create</h2>

</div>
</body>
</html>

Upvotes: 0

Views: 3954

Answers (2)

magicalex
magicalex

Reputation: 937

If you want to center the box and its contents both vertically an horizontally you could do it with absolute positioning and negative margins as can be seen in this jsfiddle.

Upvotes: 0

mrtsherman
mrtsherman

Reputation: 39872

Because #content has a width, you can set the left and right margins to auto. This will center the element in its parent. The short bit of code margin: 0 auto; sets top/bottom margin to zero and left/right to auto.

http://jsfiddle.net/vL5r2/

#content {
    margin: 0 auto;
    width:500px; 
    ...

Upvotes: 2

Related Questions