How to center a div using CSS?

0

To center a div element using CSS, you can use the margin: auto and width properties.

Here is an example:

div.center {
  width: 50%; /* Set the width of the element */
  margin: auto; /* Center the element horizontally */
}

You can also use the text-align property to center the contents of the div.

Here is an example:

div.center {
  text-align: center; /* Center the contents of the element */
}

If you want to center the div vertically as well, you can use the position, top, and left properties.

Here is an example:

div.center {
  position: absolute; /* Position the element */
  top: 50%; /* Center the element vertically */
  left: 50%; /* Center the element horizontally */
  transform: translate(-50%, -50%); /* Adjust the position of the element */
}

Note that the above methods may not work if the parent element does not have a specified height. In that case, you can use the display: flex and align-items: center properties to center the div vertically.

Here is an example:

div.parent {
  display: flex; /* Make the parent element a flex container */
  align-items: center; /* Center the child element vertically */
}

Leave a Comment

Skip to content