【问题标题】:How can the pseudo element detect the height of the non-pseudo element?伪元素如何检测非伪元素的高度?
【发布时间】:2011-09-19 18:17:20
【问题描述】:

请看http://jsfiddle.net/ZWw3Z/

<p>Text text text text text text text...</p>
p {
    background-color: blue;
}

p:before {
    content: '';
    position: absolute;
    width: 10px;
    height: 100%;
    background-color: red;
}

本质上,伪元素的高度太大了。我希望它与p 元素具有相同的高度。我该怎么做?

【问题讨论】:

    标签: css pseudo-element


    【解决方案1】:

    对于未来的读者来说,效果是在左侧的文本上方出现一个条形图。为此,OP 在伪元素 (p:before) 上使用了position: absolute;

    OP 遇到的错误是因为伪元素将 &lt;body&gt; 视为它的相对位置点 - 要修复,只需在 &lt;p&gt; 标记上设置 position: relative;

    p {
      position: relative;
      background-color: blue;
      padding-left: 10px;
      /* change the padding to something larger 
      than the width of the :before element to 
      add spacing for text
      */
    }
    
    p:before {
      content: '';
      position: absolute;
      left: 0;
      top: 0;
      width: 10px;
      height: 100%;
      background-color: red;
    }
    &lt;p&gt;text... text...&lt;/p&gt;

    【讨论】:

    • 您不需要外部容器。 p 本身包含 p:before,因此您可以简单地相对定位 p
    猜你喜欢
    • 2014-06-08
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    相关资源
    最近更新 更多