我有一个无序列表,每行都有一定的大小,每行都有一个背景,我希望调整背景的大小并完美地适合(按比例缩小)以适合框的宽度,我已经尝试过并且无法让它工作,我在这个 JSFiddle 中制作了一个简化版本 -
https://jsfiddle.net/p91vef0j/
HTML
<ul>
<li style='border: 1px solid black; background: url(http://i67.tinypic.com/xlcq5w.jpg)'>
<span style="background-color: #000000">
Marvel's Avengers Assemble - S3E1 </br>
Adapting to Change
</span>
</li>
</ul>
CSS
li{
list-style:none;
color: white ;
padding-left: 0pt;
margin-top:0px;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
height: 60px;
width: 270px;
}
ul {
padding-left: 0px;
padding-top: 0px;
}
希望有人能帮我把图片缩放到盒子里。
最佳答案
您的问题是您在 CSS 中设置 background-size: cover
但通过内联样式设置 background
。 background
是一个简写属性,包括以下内容:
背景大小
背景色
背景图片
背景位置
背景重复
背景附件
当您为 background
属性设置值时,该 URL 将应用于 background-image
,而其他属性将设置为它们的初始值。下面是spec的内容说:
Given a valid declaration, for each layer the shorthand first sets the corresponding layer of each of ‘background-image’, ‘background-position’, ‘background-size’, ‘background-repeat’, ‘background-origin’, ‘background-clip’ and ‘background-attachment’ to that property's initial value, then assigns any explicit values specified for this layer in the declaration. Finally ‘background-color’ is set to the specified color, if any, else set to its initial value.
这可以防止您的 background-size
(通过 CSS 设置)产生任何影响。
您应该使用内联样式直接设置 background-image
(或者)再次设置 background-size
。
li {
list-style: none;
color: white;
padding-left: 0pt;
margin-top: 0px;
background-size: cover;
height: 60px;
width: 270px;
}
ul {
padding-left: 0px;
padding-top: 0px;
}
<ul>
<li style='border: 1px solid black; background: url(http://i67.tinypic.com/xlcq5w.jpg); background-size: cover;'>
<span style="background-color: #000000"> Marvel's Avengers Assemble - S3E1 <br> Adapting to Change</span>
</li>
<li style='border: 1px solid black; background-image: url(http://i67.tinypic.com/xlcq5w.jpg);'>
<span style="background-color: #000000"> Marvel's Avengers Assemble - S3E1 <br> Adapting to Change</span>
</li>
<li style='border: 1px solid black; background-image: url(http://i67.tinypic.com/xlcq5w.jpg); background-size: 100% 100%'>
<span style="background-color: #000000"> Marvel's Avengers Assemble - S3E1 <br> Adapting to Change</span>
</li>
</ul>
注意:您可能还需要考虑更改 background-size
值。 cover
选项在保持纵横比不变的同时缩放图像。因此,如果图像的纵横比与 li
的纵横比不同,图像将在右侧和/或底部被裁剪。如果你想避免裁剪,你可以使用 100% 100%
作为值(就像上面代码片段中的第 3 个 li
)。
关于html - 在无序列表中调整背景图像的大小 (li),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35970065/