I have a div inside a div.
The div inside is wider than its parent so the normal procedure
margin-left: auto;
margin-right: auto;
produces an inner div where the left edge of the child aligns with the left edge of the parent.
When people answers this question, they uses to go for the negative left margin approach. Is there a cleaner solution?
use text-align:center for div -> this will align text inside div center. include width property in div (i.e. width:200px) and it will work fine.
To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.
You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.
Like last time, you must know the width and height of the element you want to center. Set the position property of the parent element to relative . Then set the child's position property to absolute , top to 50% , and left to 50% . This just centers the top left corner of the child element vertically and horizontally.
You can use flexbox:
.outer {
display: flex; /* Magic begins */
justify-content: center; /* Center contents */
width: 400px;
height: 400px;
background: beige;
margin: 0 auto;
}
.inner {
flex-shrink: 0; /* Don't shrink it even if it's too wide */
width: 600px;
height: 200px;
background: pink;
}
<div class="outer">
<div class="inner"></div>
</div>
I worked out an easy way for absolute elements using a transform.
left: 50%;
transform: translateX(-50%);
Will center it if wider than parent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With