Home »
CSS
How to horizontally center a DIV using CSS?
CSS | Centering a DIV: In this tutorial, we will learn how to horizontally center a DIV using CSS. Learn with the help of examples.
By Anjali Singh Last updated : July 11, 2023
Introduction
Working with DIVs has become a regular thing and divs are used for many purposes to mention such as they are used to structure our code and to segregate our various sections of codes. Besides, we know of many properties that we can simply just to make our website or web page responsive.
So, one must keep learning numerous properties or functions or methods and many such useful things for your web development. If you are a beginner, then it is a must that you keep learning new things for creating responsive and attractive websites or web pages. Although, there are times when we forget about the properties or functions to be implied. In that case, you can always refer to articles like these and there are abundant things out there for you to learn and grow as a good and professional web developer.
The real task here is to centrally align the DIV. The DIVs as we know are used for structuring the code so that the code becomes sorted and neat as well. Besides, by using DIVs many classes are defined that make the work quite easy as well. It is a good habit to use DIVs wherever possible in your code. To give your code a proper structure and if you want your code to appear neat, using DIVs is a must. Not just that but using DIVs you can create different sections in your website or web page ad you can assign various ids as well.
How to horizontally center a DIV using CSS?
To horizontally center the div in a webpage in CSS all you need to do is set the margin to 0 auto so that the zero will make our div a zero margin vertically and an auto-adjust margin horizontally. And put the text-align as the center. Note that you can set the width of your choice to make this trick work.
Let's make it clear by looking at the syntax,
element {
margin: 0 auto;
width: value;
text-align: center;
}
Example to horizontally center a DIV using CSS
<html>
<head>
<style>
div {
margin: 0 auto;
width: 400px;
text-align: center;
font-size: 40px;
background-color: #f40;
color: #fff;
}
</style>
</head>
<body>
<h1>This is IncludeHelp</h1>
<div>
<p>How to horizontally center a div?</p>
</div>
</body>
</html>
Output
Conclusion
In the above example, note that the paragraph written inside the div tag is aligned at the center of the webpage horizontally. So as you can see that it was not that tough, just by making use of properties here and there and you got what you wanted.
Pretty easy right? For some of you, this might be a new thing as well, aligning divs centrally comes in handy very much. So, what are you waiting for? Go ahead and start making use of new-found knowledge! The most important thing is, do not forget to have fun!
CSS Examples »