Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS display-table width 100% - missing pixel?

Tags:

html

css

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? :)

overlay

http://jsfiddle.net/v13mdq57/

like image 936
Wordpressor Avatar asked Nov 27 '22 15:11

Wordpressor


1 Answers

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>
like image 139
misterManSam Avatar answered Dec 18 '22 19:12

misterManSam