How to set a div in the center of a web browser using margins?

This is a first article from the tutorial CSS website design using divs explaining what can be achieved using auto margins in CSS.

Lets create an empty page first.

<html>
<head>
<style type="text/css">
</style>
<body>
</body>
</html>

Let’s add a 200px fixed length square div and color it red.

<html>
<head>
<style type="text/css">
div.A {background-color:red; width:200px; height:200px;}
</style>
<body>
<div class="A">This is a red div</div>
</body>
</html>

Now here comes the trick. How to center it in the browser center, only by modifying its stile.

<html>
<head>
<style type="text/css">
div.A {
background-color:red; width:200px; height:200px;
margin-left:auto; margin-right:auto;}
</style>
<body>
<div class="A">This is a red div</div>
</body>
</html>

The master design tip we used here is the margin:auto set for both margin-left and margin-right.

Inside the red div you can organize another divs to configure 1-column, 2-column, 3-column or other complex layouts. In the next article I will describe how to add child divs to a parent div to organize the layout.

tags: & category: -