[英]how to stretch or fit a background image using css attribute background in a class
[英]How to stretch and reduce background image for text label using css
我正在设计一个网页,其中包含背景图像,例如标签的箭头。 我已经在Photoshop中设计了图像。 我的问题是图像的大小没有按照文本扩大和缩小。 所以请帮助我,我该怎么办? 有什么方法可以做到这一点?
HTML:
<label><span>First Name</span></label>
CSS:
label
{
background-image:url('./images/lblimg.png');
width:auto;
display:inline-block;
}
span
{
line-height:50px;text-align:center;
}
使用样式:
background-size: cover;
background-repeat: no-repeat;
使用background-size:cover
图像将尽可能大,以便完全覆盖背景区域。
您需要将with
和height
的background-size
属性设置为100%
。
.bgimg{ background-image: url(https://cdn4.iconfinder.com/data/icons/defaulticon/icons/png/256x256/arrow-right.png); background-size: 100% 100%; font-size: 40px; color: yellowgreen; }
<span class="bgimg"> div with little text :) </span> <br /> <span class="bgimg"> div with more and more and more text :) </span>
您有两个选择,都使用CSS3 background-size
:
使用background-size: cover
:背景图像将尽可能大,直到覆盖整个背景区域。
使用background-size: 100% 100%
:背景图像将占据容器宽度和高度的100%。
在您的特定情况下,第二个选项会更好,因为您希望显示整个箭头而不会冒某些部分被隐藏的风险。
在您的代码中,它看起来像这样:
label
{
background-image:url('./images/lblimg.png');
background-size:100% 100%;
width:auto;
display:inline-block;
}
编辑(按照OP的CSS2请求): 除非您更改HTML代码,否则不能仅通过CSS2来实现 。 在那种情况下,您实际上不是在使用背景图像,而是直接在文本后面使用图像。
这是HTML的外观:
<label>
<img src="http://lorempixel.com/400/200/animals/" alt="Random pic" />
<span>First Name</span>
</label>
这是CSS的外观:
label {
width:auto;
display:inline-block;
position:relative;
}
span {
line-height:50px;text-align:center;
position:relative;
z-index:2;
}
img {
position:absolute;
z-index:1;
top:0;
left:0;
width:100%;
height:100%;
}
您可以在此JSFiddle上看到CSS3和CSS2解决方案的示例: http : //jsfiddle.net/othnjk5x/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.