1

当我在 a 中放置一个固定大小的 display-block<span>元素时,<div>它会在<div>. 当元素内有文本时<span>,一切都很好。这是什么原因?我该如何解决?我在 Firfox 和 Chrome 上进行了测试。

奇怪的空间 http://picster.at/img/0/9/6/0968c75ddf29ad07cb71eee2cff472a9.png

<!DOCTYPE html>
<html>

<head>
    <style type="text/css">
    <!--
    .outer {
        background: grey;
        padding: 4px;
    }
    .inner {
        display: inline-block;
        background: cyan;
        height: 40px;
        width: 40px;
    }
    -->
    </style>
</head>

<body>
    <div class="outer">
        <span class="inner">Foo</span>
    </div>

    <br>

    <div class="outer">
        <span class="inner"></span>
    </div>
</body>

</html>

更新:

浮动将是显示块元素的替代方案。完全有效,但是我想了解此示例中的显示块有什么问题。此外,对我来说,它看起来不像是空白问题,因为这只会影响左/右的边距(如果我错了,请纠正我)。

4

4 回答 4

3

这是因为您正在使用inline-block;,这是inline-blockfloats

演示

.outer {
    background: grey;
    padding: 4px;
    overflow: hidden;
}

.inner {
    float: left;
    background: cyan;
    height: 40px;
    width: 40px;
}

inline-block留下 4px 边距的空白。

更多信息

于 2013-04-24T09:40:15.210 回答
3

这个 hack 对我很有用。

演示

.inner:after{
        content: '\00a0';
}
于 2013-04-24T09:47:30.830 回答
1

inline-block 搞砸了

如果您将其设置为 inline-block 的意图是设置一行 .inner,则将内部设置更改为块,然后向左浮动。

然后使用带有 clear: both 的 div 来解决通常浮动导致的问题。

这是您修改的代码:

<head>
    <style type="text/css">
    <!--
    .outer {
        background: grey;
        padding: 4px;
    }
    .inner {
        display: block;
        background: cyan;
        height: 40px;
        width: 40px;
        float: left;
        margin-right: 4px;
    }
    .clear{
        clear:both;
    }
    -->
    </style>
</head>

<body>
    <div class="outer">
        <span class="inner">Foo</span>
        <div class="clear"></div>
    </div>

    <br>

    <div class="outer">
        <span class="inner"></span>
        <span class="inner"></span>
        <div class="clear"></div>
    </div>
</body>

</html>
于 2013-04-24T09:45:49.163 回答
1

它可以通过将外部元素的“行高”设置为 0 来解决。这几乎解决了所有情况。

不要忘记确保内部元素不会继承它,为此您只需将其设置为“line-height:initial”。

.outer {
        background: grey;
        padding: 4px;
        line-height:0;
    }
    .inner {
        display: inline-block;
        background: cyan;
        height: 40px;
        width: 40px;
        line-height:initial;
    }
于 2016-02-12T13:44:03.187 回答