【问题标题】:How to display the :after content outside element如何在元素外显示:after内容
【发布时间】:2012-04-10 02:08:58
【问题描述】:

在以下情况下,如何使:after 生成的文本位于跨度框之外? (它目前在内部渲染,即它使span 元素更宽)

HTML

<span class="my">Boxtext</span>

CSS

span.my {
    padding:            4px 8px;
    background-color:   red;
    display:            inline-block;
    border-radius:      10px;
    margin-left:        20px;
    }   
span.my:after {
    content:            " text that is supposed to come after the box";
    }

我猜这有点类似于list-style-position,你可以选择inside or outside...

【问题讨论】:

    标签: html css


    【解决方案1】:

    我相信 CSS 内容被认为是呈现它的对象的一部分。您可以提出 :after 应该被命名为 :append 的论点。

    对于您的情况,您可以尝试在 span.my 中添加一个额外的元素:

    <span class="my"><span>Boxtext</span></span>
    span.my span { ... }
    span.my:after { ... }
    

    或者专门设置内容的样式。

    span.my:after { 
        content:            " text that is supposed to come after the box";
        background-color:   white;
        position:           absolute;
        margin-left:        10px;
    }
    

    【讨论】:

    • 谢谢,但正如您所提到的,由于边框(-radius),第二种解决方案看起来令人不快。对于第一个解决方案,我想这会起作用,但我一直在寻找一种适用于我的原始 html 的解决方案。
    • 看了这个答案后,我破解了这个例子:jsfiddle.net/cawgZ
    • 使用绝对定位,可以让第二种方案看起来更好看。 jsbin.com/ibuqip
    • @Ben,您可能必须明确指定宽度才能克服这个问题。
    • 我会选择解决方案 1。谢谢。
    【解决方案2】:

    只需在 ::after {} 伪元素的 css 中使用 position: absolute

    span.my:after {
        content: " text that is supposed to come after the box";
        position: absolute;
        left: 100%;
    }​
    

    当然,请记住在父 span.my 元素上使用 position: relative;(或任何其他 position 值)。

    JS Fiddle demo.

    还请记住,由于::after(和::before)伪元素继承自它“附加”到的跨度,因此它将继承width,因此可能需要在其中显式覆盖那个/那些元素的 CSS。

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 2022-11-20
      • 2019-11-25
      • 2014-07-21
      • 2016-05-24
      • 2023-01-26
      • 2019-01-30
      • 2015-09-12
      • 1970-01-01
      相关资源
      最近更新 更多