I have a div
that I want to center horizontally and vertically.
For the horizontal issue everything is great, but I have a problem with the vertical alignment.
I tried this:
#parent {
display: table;
}
#child {
display: table-row;
vertical-align: middle;
}
but this doesn't work.
If you only have to support browsers that support transform
(or its vendor prefixed versions), use this one weird old trick to vertically align elements.
#child {
position: relative;
top: 50%;
transform: translateY(-50%);
}
If you have to support older browsers, you can use a combination of these, but they can be a pain due to the differences in rendering block
vs table
.
#parent {
display: table;
}
#child {
display: table-cell;
vertical-align: middle;
}
If your height is fixed and you need to support those really old, pesky browsers...
#parent {
position: relative;
}
#child {
height: 100px;
position: absolute;
top: 50%;
margin-top: -50px;
}
If your height is not fixed, there is a workaround.
See it on jsFiddle.
Having the parent property as, display:table
and child property as display: table-cell
and vertical-align: middle
worked for me.
You can use flexbox
to center horizontally or vertically your child div
inside a parent div
:
This should be your html:
<div id="parent">
<div id="child">
info
</div>
</div>
And this is the css
with flexbox
:
#parent{
display: flex;
align-items: center;
justify-content: center;
position: relative;
width: 100%;
height: 100vh;
background: lightgray;
}
#child{
position: relative;
background: black;
padding: 2rem;
color: white;
box-shadow: 5px 5px 20px rgba(0,0,0,.4);
border-radius: 5px;
}
Here is de codepen: https://codepen.io/bongardabo/pen/YzZQgaJ
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