【问题标题】:avoid span float right overlap with text (CSS)避免跨度浮动与文本(CSS)重叠
【发布时间】:2014-02-12 16:50:26
【问题描述】:

我正在使用人力车,并有一个图表悬停/注释,其中颜色样本(使用 <span> 定义)与 <div> 中的文本重叠,它们都包含在其中。

这是我的 HTML:

<div class="detail" style="left:250px">
    <div class="item active" style="top: 200px"> 
        <span style="background-color: #30c020" class="detail_swatch"></span>
        Very very very very very long label: 67<br/>
        <span style="color:#A0A0A0">Wed, 12 Feb 2014 18:51:01 GMT</span>
    </div>
</div>

这是我的 CSS:

.detail {
    position: absolute;
}
.detail .item {
    position: absolute;
    padding: 0.25em;
    font-size: 12px;
    font-family: Arial, sans-serif;
    color: white;
    white-space: nowrap;
}
.detail .item.active {
    opacity: 1;
    background: rgba(0, 0, 0, 0.8);
}
.detail_swatch {
    display: inline-block;
    float: right;
    height: 10px;
    margin: 0 4px 10px 10px;
    width: 10px;
}

detail_swatch 正确显示在右上角,但会与very very ... long label 重叠。我读过的大多数解决方案都涉及更改包含 div 的位置语句。这不是一个选项。

有什么方法可以确保detail_swatch 不与文本重叠,而是扩展它们包含的div(水平)?

此代码可在 JSFiddle here 上找到,它也显示了问题。

【问题讨论】:

标签: html css css-float rickshaw


【解决方案1】:

您可以在.detail .item.active {} 中添加padding-left: 15px;,以确保该项目不会被文本重叠。然后我将.detail_swatch 设置为绝对定位而不是float: right;,这样它就与我添加的填充重叠了。

这是更改后的 css:

.detail .item.active {
    opacity: 1;
    background: rgba(0, 0, 0, 0.8);
    padding-right: 15px;
}
.detail_swatch {
    display: inline-block;
    position: absolute;
    right: 2px;
    height: 10px;
    margin: 0 4px 10px 10px;
    width: 10px;
}

最后,提琴:Demo

摆弄非常长的文字:Demo

【讨论】:

  • 它适用于中间有空格或“破折号”的文本。但是当文本之间没有空格或破折号时如何避免重叠。
【解决方案2】:

如果您希望元素具有固定宽度,您可以使用text-overflow: ellipsis

jsfiddle

.detail .text {
    display: inline-block;
    max-width: 90%;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
}

【讨论】:

    【解决方案3】:

    问题的根本原因是 span 是一个内联元素,它旨在内联显示。您希望包含日期的跨度表现得像块级元素,因此您选择的元素是错误的。

    解决方法很简单;使用 div 而不是 span 来包含日期并删除 br。

    【讨论】:

      猜你喜欢
      • 2023-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-21
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      相关资源
      最近更新 更多