[英]Does background-size:cover make background-position:center and background-repeat:no-repeat unnecessary?
Learning css, and I had a question about background-size: cover
.学习 css,我有一个关于
background-size: cover
。 Everything is working, but all guidance I look at tells me to also include background-repeat: no-repeat
and background-position: center
if I want a background image that does not repeat and is centered.一切正常,但我看到的所有指导都告诉我还包括
background-repeat: no-repeat
和background-position: center
如果我想要一个不重复且居中的背景图像。 Shouldn't background-size: cover
be sufficient for centering the image and stopping it from repeating? background-size: cover
应该足以使图像居中并阻止其重复吗? I'd love to trim unnecessary lines, but before I do, I'm wondering whether someone with more experience can point out a misunderstanding or edge cases the additional rules take care of.我很想修剪不必要的线条,但在此之前,我想知道是否有更多经验的人可以指出附加规则处理的误解或边缘情况。
.main {
background-image: url("#");
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
While the question looks opinion-based at first sight, and the answer seems to be "it doesn't matter", the reality is it does.虽然这个问题乍一看似乎是基于意见的,答案似乎是“没关系”,但事实是确实如此。
Take this example where you put a 100×100 image as a background in a 300×150 container.以这个例子为例,你将一张 100×100 的图像作为背景放在一个 300×150 的容器中。
In the absence of any other styles, the background-position is 0% 0%
(see W3C ) and it looks like this:在没有任何其他样式的情况下,背景位置为
0% 0%
(参见W3C ),它看起来像这样:
div { width:300px; height:150px; background-image: url('https://via.placeholder.com/100x100'); background-size:cover; }
<div></div>
where the image is stretched to 300×300 to fit the div, and the result shows only the top half of the image.其中图像被拉伸到 300×300 以适应 div,结果只显示图像的上半部分。
Then, adding background-position:center
results in this:然后,添加
background-position:center
结果如下:
div { width:300px; height:150px; background-image: url('https://via.placeholder.com/100x100'); background-size:cover; background-position:center; }
<div></div>
where the middle half of the image is shown!显示图像的中间一半!
So the answer is: no, using background-size:cover
by itself doesn't center the image, and you will need background-position
to adjust.所以答案是:不,单独使用
background-size:cover
不会使图像居中,您需要调整background-position
。
Then there's the matter of background-repeat
.然后是
background-repeat
。 As was mentioned in the comments, you can position a background image in such a way that it doesn't cover the container, even if background-size
is cover
.正如评论中提到的,您可以以不覆盖容器的方式定位背景图像,即使
background-size
是cover
。 When you look at this fiddle , you will see two halves of the background image.当你看这个小提琴时,你会看到背景图像的两半。 Then if you add
background-repeat:no-repeat
to the css, there's only one half, and it will not cover the entire div.那么如果在css中添加
background-repeat:no-repeat
,就只有一半了,不会覆盖整个div。
So in that case, the answer is: it depends on your needs.因此,在这种情况下,答案是:这取决于您的需求。
Hope this helps!希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.