CSS显示表宽度100% - 丢失像素? [英] CSS display-table width 100% - missing pixel?

查看:224
本文介绍了CSS显示表宽度100% - 丢失像素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个div容器,里面有叠加层:

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>

问题是,当我将叠加显示设置为表中心的东西,垂直和水平的 - 只是简化了这个例子为SO)如下:

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%;
}



我遇到了奇怪的故障 - 虽然开发者工具告诉我覆盖有与容器相同的宽度 - 在某些情况下,覆盖宽度等于容器的宽度减去1像素。为什么?我缺少什么?如何解决这个问题? :)

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/

推荐答案

根据宽度,计算是给你一个半像素(不能渲染)。我们可以实现这个而不用 display:table 。我不太确定为什么这只发生在 display:table ,但将覆盖作为块元素修复了这个问题。

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.

在此示例中:


  • .overlay:before 将内联元素带入中间。

  • .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.

闭合和打开div标签有一个不可见的元素,

The closing and opening div tags have no white space between them, which prevents the inline gap.

详细了解如何消除内嵌元素之间的差距

CSS / HTML / Demo

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>

这篇关于CSS显示表宽度100% - 丢失像素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆