CSS display-table width 100% - missing pixel?

前端 未结 2 829
野趣味
野趣味 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;
    }
    Centered
    Centered
    Centered
    Centered

提交回复
热议问题