CSS display-table width 100% - missing pixel?

前端 未结 2 827
野趣味
野趣味 2021-01-19 01:58

I have a few div containers with overlays inside of them:

相关标签:
2条回答
  • 2021-01-19 02:15

    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>

    0 讨论(0)
  • 2021-01-19 02:28
    * {
      margin:0px;
      padding:0px;
    }
    
    .container {
      position: relative;
      display: inline-block;
      background: #fed900;
      width: 25%;
      height: 200px;
      margin-right: -3px;
    }
    
    0 讨论(0)
提交回复
热议问题