我尝试使用 background-size: cover
和 background-size: contain
将背景图像居中放置在 div 中,但它不起作用。我需要在 HTML 标签内显示背景图片并在 css 文件中使用背景大小,这是代码:
.container {
width: 200px;
height: 260px;
position: relative;
margin: 0 auto 40px;
margin-left: 20px;
display: inline-block;
}
.main{
border: 1px solid black;
background-color: #A6A6A6;
}
.card {
width: 100%;
height: 100%;
position: absolute;
border: 2px solid white;
}
.card div {
height: 100%;
width: 100%;
color: white;
text-align: center;
position: absolute;
}
.card .front {
background-repeat: no-repeat;
background-position: center center;
background-size: contain;
-webkit-background-size: contain;
-moz-background-size: contain;
-o-background-size: contain;
}
<body style="background-image:url(https://s3.amazonaws.com/Syntaxxx/background-gold-bokeh.jpg);">
<div class="main">
<section class="container">
<div class="card">
<div class="front" style="background-image: url('http://www.mobygames.com/images/covers/l/403626-injustice-2-playstation-4-front-cover.png');">
</div>
<div class="back">1</div>
</div>
</section>
<section class="container">
<div class="card">
<div class="front" style="background-image: url('http://www.mobygames.com/images/covers/l/403651-the-surge-playstation-4-front-cover.jpg');">
</div>
<div class="back">2</div>
</div>
</section>
</div>
</body>
最佳答案
您的 .card .front
具有 background-repeat
样式,您为其赋予了太多属性。
center center
需要给background-position
.card .front {
background-position: center center;
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
对于 CSS 和大多数其他维度,您先使用 X,然后使用 Y,然后使用 Z(除了 Z-index 之外没有 Z)
Background-size 会放大图片直到填满整个 div。
您正在寻找的是background-size: contain
。这将在任何容器中显示完整图像。然后添加center center
.card .front {
background-image: url(https://s3.amazonaws.com/Syntaxxx/background-gold-bokeh.jpg);
background-repeat: no-repeat;
background-position: center center;
background-size: contain;
-webkit-background-size: contain;
-moz-background-size: contain;
-o-background-size: contain;
}
关于html - 背景大小的封面/中心不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47324360/