I have a working code here: http://jsfiddle.net/WVm5d/ (you might need to make the result window bigger to see the align center effect)
Question
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;
}
.child {
display: inline-block;
}
<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.
Just use:
line-height:50px
Replace "50px" with the same height as your div.
Great article i found what worked best for me was to add a % to the size
.wrap {
margin-top:5%;
margin-bottom:5%;
height:100%;
display:block;}
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;
}
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%);
}