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

时间:2014-08-11 13:54:10

标签: html css

我正在尝试在图像上叠加一些文字,并使背景图像0.2透明。现在我的问题是:如何使伪元素的背景图像拉伸以适应宽度或裁剪图像以适应屏幕(不扭曲图像)?编辑codepen here上的代码。

的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:

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

2 个答案:

答案 0 :(得分:0)

您可以使用:

#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*/

}

或者像这样的一行语法:

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

详细信息click.

答案 1 :(得分:0)

目前还不完全清楚你要做什么,但你可以尝试添加background-size:cover,如下所示:

JSfiddle

<强> 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;

}