CSS HTML

How to center a div with CSS

November 11, 2021

How to center a div with CSS

In this post we’ll learn how to center a div in a web project, explaining all the CSS details that need to be done to achieve the goal.

How to centralize a div cover

What’s up, programmer, okay? Let’s learn something new?

Watch this content on YouTube:

Whenever we’re structuring a layout, it’s normal to need to center elements on it.

We can center texts with the text-align property and the center value, but what about a div?

The easiest way is to leave the div with position relative, and the margins left and right as auto

This will make the element centered on the CSS. Let’s see an example?

How to center a div: pratice

HTML:

<!DOCTYPE html>
<html>
 <head>
  <title>Centralizando uma div</title>
 </head>
 <body>
  <div id="container">
   <div id="center"></div>
  </div>
 </body>
</html>

CSS:

#container {
 background-color: red;
 width: 1000px;
 height: 300px;
}

#center{
 background-color: blue;
 width: 100px;
 height: 100px;
}

It returns the following result: 

how to center a div in html

And now let’s apply the aforementioned rules:

#center {
 background-color: blue;
 width: 100px;
 height: 100px;
 position: relative;
 margin-left: auto;
 margin-right: auto;
}

And the div will be centered:

So these are the steps needed to centralize a div in an HTML block

The div could also be an absolute position, so the way to center is a little different

I suggest you dig a little deeper and know at least: absolute, relative and fixed

Which are the most used in most projects

Conclusion

In this article we learned how to centralize a div in an HTML project

We just insert the position of a div as relative, and the marginal-left and margin-right properties as auto

So the div we need to be centered will be positioned in the center of the parent element.

Want to improve your CSS skills? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x