I have a few div containers with overlays inside of them:
<div class="container">
<div class="overlay"></div>
</div>
<div class="container">
<div class="overlay"></div>
</div>
<div class="container">
<div class="overlay"></div>
</div>
<div class="container">
<div class="overlay"></div>
</div>
The problem is, when I set overlay display to table (it has to be table as I'm centering stuff both vertically & horizontally there - just simplified this example for SO) like so:
.container {
position: relative;
display: inline-block;
background: #fed900;
outline: solid 5px #000;
width: 25%;
height: 200px;
}
.overlay {
position: absolute;
top: 0;
display: table;
background: rgba(0,0,0,0.4);
width: 100%;
height: 100%;
}
I'm getting weird glitch - although developer tools tell me the overlay has the same width as container - in some cases the overlay width equals container's width minus 1 pixel. Why? What am I missing? And how to fix that? :)
http://jsfiddle.net/v13mdq57/
Depending on the width, the calculation is giving you a half pixel (which can't be rendered). We can achieve this without display: table
. I'm not quite sure why this only occurs with display: table
, but leaving the overlay as a block element fixes the problem.
In this example:
.overlay:before
brings inline elements into the middle. It is an invisible element that is lined up on the left hand side inside the overlay.
The closing and opening div tags have no white space between them, which prevents the inline gap.
Read more about removing the gap between inline elements.
CSS / HTML / Demo
body {
margin: 0;
}
.container {
position: relative;
display: inline-block;
vertical-align: middle;
background: #fed900;
width: 25%;
height: 200px;
}
.overlay:before {
content:'';
display: inline-block;
height: 100%;
vertical-align: middle;
}
.overlay {
position: absolute;
top: 0;
left: 0;
background: rgba(0, 0, 0, 0.4);
width: 100%;
height: 100%;
text-align: center;
}
<div class="container">
<div class="overlay">Centered</div>
</div><div class="container">
<div class="overlay">Centered</div>
</div><div class="container">
<div class="overlay">Centered</div>
</div><div class="container">
<div class="overlay">Centered</div>
</div>
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