How can I horizontally center an element?
January 10 2023
we have different types of options are available to horizontally center an element in CSS, depending on the situation. We will look at those details one by one.
margin: auto:
Using margin: auto: using this method works if the element you want to center is a block-level element, and its parent has a defined width. You can set the element's left and right margins to auto,
.center {
margin: 0 auto;
}
flexbox:
Using flexbox: You can use the display: flex property on the parent element, and then use the align-items: center and justify-content: center properties on the child element.
.parent {
display: flex;
align-items: center;
justify-content: center;
}
grid :
Using grid : Similarly, you can use the display: grid property on the parent element and use place-items: center on the child element.
.parent {
display: grid;
place-items: center;
}
transform: translateX(50%):
Using transform: translateX(50%) method uses the CSS transform property to position the element in the horizontal center of its parent element. The translateX function takes the horizontal offset as a parameter, which is set to 50% to center the element.
.center {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
text-align:
If you would like to set a fixed width on the inner div you can use the code below one:
#outer {
width: 100%;
text-align: center;
}
#inner {
display: inline-block;
}
The HTML code is,
<div id="outer">
<div id="inner">thelinuxfaq.com</div>
</div>
Comments (0)