简体   繁体   English

如何使伪元素的背景图像拉伸以适合宽度?

[英]How to make the background image of the pseudo element stretch to fit the width?

I am trying to overlay some text on an image, and also make the background image 0.2 transparent. 我正在尝试在图像上覆盖一些文本,并使背景图像0.2透明。 now my question is: How to make the background image of the pseudo element stretch to fit the width or crop the image to fit the screen(without distort the image)? 现在我的问题是:如何使伪元素的背景图像拉伸以适合宽度或裁剪图像以适合屏幕(不使图像变形)? Edit the code on codepen here . 此处在codepen上编辑代码。

css: CSS:

#main:after {
    content : "";
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    background-image: url(http://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Selwyn_College_Old_Court%2C_Cambridge%2C_UK_-_Diliff.jpg/944px-Selwyn_College_Old_Court%2C_Cambridge%2C_UK_-_Diliff.jpg); 
    width: 100%;
    height: 100%;
    opacity : 0.2;
    z-index: -1;
}

html: 的HTML:

<div id="main">
  Text on top, no big deal, no big deal. Just a little text and stuff. That's all.
</div>

You can use this: 您可以使用此:

#main:after {
content : "";
display: block;
position: absolute;
top: 0;
left: 0;
background-image: url(http://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Selwyn_College_Old_Court%2C_Cambridge%2C_UK_-_Diliff.jpg/944px-Selwyn_College_Old_Court%2C_Cambridge%2C_UK_-_Diliff.jpg); 
width: 100%;
height: 100%;
opacity : 0.2;
z-index: -1;

background-size: 100% 100%;    /* added*/
background-repeat: no-repeat;  /* optinal*/

} }

Or in one line syntax like this: 或像这样的一行语法:

background-size: auto|length|cover|contain|initial|inherit;

For more detail click. 有关更多详细信息, 请单击。

It's not entirely clear what you are tying to do but you could try adding background-size:cover as follows: 尚不清楚您要做什么,但是您可以尝试添加background-size:cover ,如下所示:

JSfiddle JS小提琴

CSS 的CSS

#main:after {
    content : "";
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    background-image: url(http://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Selwyn_College_Old_Court%2C_Cambridge%2C_UK_-_Diliff.jpg/944px-Selwyn_College_Old_Court%2C_Cambridge%2C_UK_-_Diliff.jpg); 
    background-repeat: no-repeat;

    background-size: cover;
    width: 100%;
    height: 100%;
    opacity : 0.2;
    z-index: -1;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM