How to make div center using css?
To center a <div>
element horizontally and vertically using CSS, you can use the following techniques:
1- Using Flexbox:
.container {
display: flex;
justify-content: center; /* Horizontally center */
align-items: center; /* Vertically center */
}
2- Using Grid:
.container {
display: grid;
place-items: center; /* Center both horizontally and vertically */
}
3- Using Absolute Positioning:
.container {
position: relative;
}
.centered-div {
position: absolute;
top: 50%; /* Move to the middle vertically */
left: 50%; /* Move to the middle horizontally */
transform: translate(-50%, -50%); /* Adjust position to center */
}
4- Using Text-Align:
.container {
text-align: center;
}
.centered-div {
display: inline-block;
/* Additional styles for the div if needed */
}
These methods can be applied to a container element (such as a <div>
or any other block-level element) that wraps the content you want to center. By applying the appropriate CSS rules to the container, you can achieve both horizontal and vertical centering. Feel free to choose the technique that best suits your needs and the overall structure of your HTML.