To horizontally center a div with CSS, you can use the margin property set to auto for both the left and right sides.
div {
width: 50%; /* or any width */
margin: 0 auto;
}
Here is an example of a div with a class “center” being centered horizontally within a container div:
HTML:
<div class="container">
<div class="center">
Content goes here
</div>
</div>
CSS:
.container {
width: 100%;
}
.center {
width: 50%; /* or any width */
margin: 0 auto;
}
This will center the div with class “center” horizontally within the container div, assuming that the container div has a width set and that the “center” div has a width set as well.
Also Read:
- How To Remove White Space Under An Image Using CSS
- What are Pseudo Elements And Pseudo Classes?
- Which CSS Property Is Used To Change The Face Of A Font?
- How To Change Background Opacity Without Affecting Text
- Change The Cursor Into A Hand When A User Hovers Over A List Item?
- How To Change The Color Of HR Tag With CSS