CSS :before 和 background-image... 它应该工作吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7203697/
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
:before and background-image... should it work?
提问by Michi
I've got a div and apply :before
and :after
an image as content. That works perfectly. Now I would need to apply a background image so it does repeat as the div
resizes, but it does not seem to work. Is background image on :before
and :after
supposed to be working?
我有一个 div 和 apply:before
和:after
一个图像作为内容。这完美地工作。现在我需要应用背景图像,以便它在div
调整大小时重复,但它似乎不起作用。背景图像是否打开:before
并且:after
应该有效?
The current code:
当前代码:
HTML:
HTML:
<div id="videos-part">test</div>
CSS:
CSS:
#videos-part{
background-color: #fff;
height: 127px;
width: 764px;
margin: -6px 0 -1px 18px;
position: relative;
}
#videos-part:before{
width: 16px;
content: " ";
background-image: url(/img/border-left3.png);
position: absolute;
left: -16px;
top: -6px;
}
回答by sandeep
@michi; define height
in your before
pseudo class
@米奇;height
在你的before
伪类中定义
CSS:
CSS:
#videos-part:before{
width: 16px;
content: " ";
background-image: url(/img/border-left3.png);
position: absolute;
left: -16px;
top: -6px;
height:20px;
}
回答by meo
Background images on :before
and :after
elements should work. If you post an example I could probably tell you why it does not work in your case.
:before
和:after
元素上的背景图像应该可以工作。如果您发布一个示例,我可能会告诉您为什么它在您的情况下不起作用。
Here is an example: http://jsfiddle.net/namas/3/
这是一个例子:http: //jsfiddle.net/namas/3/
You can specify the dimensions of the element in % by using background-size: 100% 100%
(width / height), for example.
例如,您可以使用background-size: 100% 100%
(width / height)以百分比形式指定元素的尺寸。
回答by Altravista
color: transparent;
make the tricks for me
为我做把戏
#videos-part:before{
font-size: 35px;
line-height: 33px;
width: 16px;
color: transparent;
content: 'AS YOU LIKE';
background-image: url('data:image/svg+xml;base64,PD94bWwgd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
The problem with other answers here is that they use position: absolute;
这里其他答案的问题是他们使用 position: absolute;
This makes it difficult to layout the element itself in relation to the ::before
pseudo-element. For example, if you wish to show an image before a link like this:
这使得很难相对于::before
伪元素来布局元素本身。例如,如果您希望在这样的链接之前显示图像:
Here's how I was able to achieve the layout in the picture:
这是我如何能够实现图片中的布局:
a::before {
content: "";
float: left;
width: 16px;
height: 16px;
margin-right: 5px;
background: url(../../lhsMenu/images/internal_link.png) no-repeat 0 0;
background-size: 80%;
}
Note that this method allows you to scale the background image, as well as keep the ability to use margins and padding for layout.
请注意,此方法允许您缩放背景图像,并保留使用边距和填充进行布局的能力。