CSS 宽度和高度似乎不适用于 :before 伪元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20858587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 01:28:52  来源:igfitidea点击:

width and height doesn't seem to work on :before pseudo-element

csspseudo-element

提问by spraff

Hereis a fiddle.

是一个小提琴。

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

and

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

The '?' appears but clearly does not have 20ex size. Why not? Tested in Firefox and Chrome.

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

回答by adrift

Note: The ::beforeand ::afterpseudo-elementsare actually laid display: inline;by default.

注意:::before::after伪元素实际上display: inline;是默认放置的。

Change the display value to inline-blockfor the width & height to take effect while maintaining inline formatting context.

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

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

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

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

回答by BoltClock

::beforeand ::afterpseudo-elements are laid inline by default, so widthand heightwon't take effect.

::before::after伪元素默认情况下,内联铺设,所以widthheight不会生效。

Set it to display: inline-blockand it should work.

将它设置为display: inline-block它应该可以工作

回答by Dmytro Yurchenko

Use this if you have image in container or CSS white-space: nowrap;property

如果您在容器或 CSS空白处有图像,请使用此选项: nowrap; 财产

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

回答by NoobEditor

add display:block;

添加 display:block;

demo

演示

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

回答by e11world

I can get it to work but not using a percentage in width. Pixels work fine

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

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