If you have a <div> with text-align:center; , then any text inside it will be centered with respect to the width of that container element. inline-block elements are treated as text for this purpose, so they will also be centered.
How to Center an Image Using Text Align: Center. An <img> element is an inline element (display value of inline-block ). It can be easily centered by adding the text-align: center; CSS property to the parent element that contains it.
To center an inline element like a link or a span or an img, all you need is text-align: center . For multiple inline elements, the process is similar. It's possible by using text-align: center .
Try using this: margin: 0 auto; Or text-align: center; on the parent <div> ...
Try this. I added text-align: center
to body and display:inline-block
to wrap, and then removed your display: table
body {
background: #bbb;
text-align: center;
}
.wrap {
background: #aaa;
margin: 0 auto;
display: inline-block;
overflow: hidden;
}
The accepted solution wouldn't work for me as I need a child element with display: inline-block
to be both horizontally and vertically centered within a 100% width parent.
I used Flexbox's justify-content
and align-items
properties, which respectively allow you to center elements horizontally and vertically. By setting both to center
on the parent, the child element (or even multiple elements!) will be perfectly in the middle.
This solution does not require fixed width, which would have been unsuitable for me as my button's text will change.
Here is a CodePen demo and a snippet of the relevant code below:
.parent {
display: flex;
justify-content: center;
align-items: center;
}
<div class="parent">
<a class="child" href="#0">Button</a>
</div>
If you have a <div>
with text-align:center;
, then any text inside it will be centered with respect to the width of that container element. inline-block
elements are treated as text for this purpose, so they will also be centered.
You can also do this with positioning, set parent div to relative and child div to absolute.
.wrapper {
position: relative;
}
.childDiv {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
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