Here's how I'd usually center align an item with absolute positioning:
img {
width: 100%;
height: auto;
}
.cat {
position: relative;
}
.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 9999;
background: #fff;
padding: 12px;
}
a,
a:visited,
a:hover,
a:focus {
color: #000;
text-decoration: none;
}
<div class="cat">
<a href="#" class="center">I want to center this</a>
<img src="https://hackernoon.com/hn-images/1*mONNI1lG9VuiqovpnYqicA.jpeg" alt="Cat being cool">
</div>
I've recently discovered that you can do the same with flexbox, like so:
img {
width: 100%;
height: auto;
}
.cat {
position: relative;
display: flex;
justify-content: center;
align-items: center;
}
.center {
position: absolute;
z-index: 9999;
background: #fff;
padding: 12px;
}
a,
a:visited,
a:hover,
a:focus {
color: #000;
text-decoration: none;
}
<div class="cat">
<a href="#" class="center">I want to center this</a>
<img src="https://hackernoon.com/hn-images/1*mONNI1lG9VuiqovpnYqicA.jpeg" alt="Cat being cool">
</div>
Is there any benefit to using the flexbox solution? A major downside I'm seeing is browser compatibility. I can't find a solution that purely uses flexbox.