user3475954
user3475954

Reputation:

Put body content in center

I use center tag, but it seems that is not standard in HTML 5. I tried to use CSS instead but it doesn't work for me! I expect in this example the div tag be displayed in center but it won't.

<!doctype html>
<html>
<body style="text-align:center">
<div style="width:100px; height:30px; background-color:rgb(0,0,0)"></div>
</body>
</html>

And this is center tag version: (it works)

<!doctype html>
<html>
<body>
<center>
<div style="width:100px; height:30px; background-color:rgb(0,0,0)"></div>
</center>
</body>
</html>

Upvotes: 1

Views: 362

Answers (3)

user3544556
user3544556

Reputation:

The div tag which you want to put in center in your body must be :

.div-class {
    margin: auto;
}

If you use margin top or bottom, you can do this way:

.div-class {
    margin-left: auto;
    margin-right: auto;
}

Upvotes: 0

Felix
Felix

Reputation: 38112

You can use margin: auto for your div

div {
    margin: auto;
    width:100px; 
    height:30px; 
    background-color:rgb(0,0,0)
}

Also it's better to give your div an id or class name to target it more accurately if your HTML markup become more complex as well as using external CSS instead of inline styles like what you're doing now.

Fiddle Demo

Upvotes: 3

Nick
Nick

Reputation: 461

You can use css:

.window{
    position:absolute;
    top:50%;
    left:50%;
    margin-top:-140px;
    margin-left:-200px;
    width:400px;
    height:280px;
}

make sure you substract half of the width and height using margins. This way your div will be centered within the window the div is in.

Upvotes: 0

Related Questions