【问题标题】:width and height doesn't seem to work on :before pseudo-element宽度和高度似乎不适用于 :before 伪元素
【发布时间】:2014-01-18 11:06:42
【问题描述】:

Here 是个小提琴。

<p>foo <a class="infolink" href="#">bar</a> baz</p>

a.infolink::before
{
    content: '?';
    background: blue;
    color: white;
    width: 20ex;
    height: 20ex;
}

“?”出现但显然没有 20ex 大小。为什么不?在 Firefox 和 Chrome 中测试。

【问题讨论】:

    标签: css pseudo-element


    【解决方案1】:

    如果将元素设置为position: relative设置为position: absolute,则可以调整伪宽度height 相对于父元素的大小。

    div {
        position: relative;
        width:400px;
        height:200px;
        padding: 0;
    }
    
     div::before {
        position: absolute;
        width:100%;
        height: 100%
    }
    

    【讨论】:

      【解决方案2】:

      对我来说,当我使用 display: block 时它起作用了。

      【讨论】:

        【解决方案3】:

        注意:::before::after pseudo-elements 实际上默认为 display: inline;

        将显示值更改为 inline-block 以使宽度和高度生效,同时保持内联格式设置上下文。

        a.infolink::before {
            content: '?';
            display: inline-block;
            background: blue;
            color: white;
            width: 20px;
            height: 20px;
        }
        

        http://jsfiddle.net/C7rSa/3/

        【讨论】:

        • 不错的解决方案..但是当内容具有 base64 图像字符串时这不起作用...在 firefox 45.3 上测试
        • base64 图像你成功了吗?
        • @Webwoman:请更具体一点——如果您指的是通过宽度/高度控制图像大小,那么这不是它应该工作的方式。这些属性只控制伪元素本身的大小,而不是它的内容。
        • 我一直忘记这个事实,似乎总是不时回到这里;)
        【解决方案4】:

        如果您在容器或 CSS white-space: nowrap; 属性中有图像,请使用此属性

        body::before{ 
            content:url(https://i.imgur.com/LJvMTyw.png);
            transform: scale(.3);
        }
        

        【讨论】:

          【解决方案5】:

          我可以让它工作,但不使用宽度百分比。像素工作正常

          visibility: visible;
          content: "stuff";
          min-width: 29px;
          width: 100%;
          float: left;
          position: relative;
          top: -15px;
          left: 0;
          

          【讨论】:

          • 这通常是因为您没有在创建伪元素的元素上设置宽度。在这种情况下,百分比没有任何不同。
          【解决方案6】:

          添加display:block;

          demo

          p > a.infolink::before {
              display:block;
              content:'?';
              background: blue;
              color: white;
              width: 20ex;
              height: 20ex;
              border:1px solid #000;
          }
          

          【讨论】:

            【解决方案7】:

            ::before::after伪元素默认是内联的,所以widthheight不会生效。

            将其设置为display: inline-blockit should work

            【讨论】:

              猜你喜欢
              • 2011-09-29
              • 2019-05-03
              • 2015-05-06
              • 1970-01-01
              • 2013-02-04
              • 2014-06-08
              • 1970-01-01
              • 2012-08-20
              • 2017-02-21
              相关资源
              最近更新 更多