How to center div horizontally using CSS

Hi guys, today I would like to explain something about a problem that I had when I was a beginner, how to center a div horizontally and close to the top of the page using css.
This lesson is very simple.
The first thing we’re going to do is to write our markup html:

<div>
Put your content here
</div>

Now we have to use css to center div horizontally:

div {width:960px; margin:0 auto;}

This code is very simple so I didn’t use any class or id but if your code is bigger you can use it:

<div class="content">
Put your content here
</div>

CSS:

div.content{width:960px; margin:0 auto;}

To center div horizontally we have to give a fixed width to it and give auto margin-left and right. The margin-top is set to “0” so the div will start from the top of the page. If we want the div start away from the top we have to write something like this: margin: 10 auto.
In CSS, to set box’s margins we can can write some different types of code, below there are examples about it:

div{
margin: 10px 20px 10px 20px;
}

we showed the margins clockwise from the top to the left.

div{
margin: 0 auto;
}

The first value is for the margin-top and the bottom, the second one is for left and right.

div{
margin: 10px 2em 2%;
}

The first margin is for the top, the second one is for left and right, the third is for the margin bottom.
Now we have learnt how to center div horizontally and how to write css style for margins attribute.
If you want to know more about this lesson click here and visit the W3 web site.
That’s all guys! I hope to be clear about how to center div horizontally and your work is going to be good!


Se ti è piaciuto questo articolo o ti è stato utile in qualche modo, lascia un commento, condividilo con i tuoi amici e seguimi sui social.

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *

Questo sito usa Akismet per ridurre lo spam. Scopri come i tuoi dati vengono elaborati.

La mia newsletter

Ricevi gratuitamente contenuti esclusivi e aggiornamenti sui nuovi articoli. Non saranno troppi! :)

    X