Introduction
It is sometimes required, when building a website to center a part of your website on the screen and this is a notoriously vague system for acheiving this effect. In this brief tutorial I will explain the system for centering an element in this manner.
introduction to CSS margin
CSS comes with an ability to add margins to the edges of an element in the page, and it using these that the element will be centered horizontally, by setting the margin to auto, the margins on the left and right had side of the element will be equal to each other, this will push the element into the center of the window. Here is the CSS we will use:
Margin: auto;
This directive will work on any CSS element which is display: block, we can ensure our element is set to display: block, by defining a width, here is the full styling used to center an element:
.centered{
display: block;
width: 250px;
height: 50px;
margin: auto;
background-color: blue; /*added so it can be seen in the example! */
}
Now to use this we will create a div and give it a class of centered:
Conclusion
This has created a centered div (it is colored blue so you can see it, you can remove the line that colors it, or change the color to something else to color it how you'd like.
I hope this article helped, please contact us if you have any questions, or suggestions for articles you'd like to see!
