CSS对象适合封面是拉伸图像

时间:2018-06-18 06:14:20

标签: css object-fit

CSS对象适合位置fillcontain正在运行,但cover的工作方式与fill类似。无论图像的多少部分是cover,它都必须填充div 而不拉伸。我将div设置为flex并将object fit position应用于div中的图像。为什么cover不起作用?如果我在px中设置高度以使图像有效,但是图像必须根据div调整大小,所以我设置高度auto



<html>
<head>
<style>
.left{
  float:left;
}
.col100{
  width:100%; 
 }
.col33{
  width:33%;
}
.h30{
  height:30vw; 
 }
 .mright10{
  margin-right:10px;
 }
.bgred{
  background:red;
 }
 .bold{
  font-weight:bold;
 }
 .cover{
  object-fit: cover;
 }
.contain{
  object-fit: contain;
 }
.fill{
  object-fit: fill;
 }
 .flex{
  display:flex;
 }
</style>
</head>
<body>
<div class="left col33 mright10">
<p class="left col100">Original Size</p>
<section class="col100 left h30 bgred">
  <img class="col100" src="https://www.gstatic.com/webp/gallery/1.sm.jpg" />
</section>
</div>

<div class="left col33">
<p class="left col100">contain</p>
<section class="col100 left h30 bgred flex">
  <img class="col100 cover contain" src="https://www.gstatic.com/webp/gallery/1.sm.jpg" />
</section>
</div>

<div class="left col33 mright10">
<p class="left col100">fill</p>
<section class="col100 left h30 bgred flex">
  <img class="col100 cover fill" src="https://www.gstatic.com/webp/gallery/1.sm.jpg" />
</section>
</div>

<div class="left col33">
<p class="left col100 bold">Cover - but image is being stretched !</p>
<section class="col100 left h30 bgred flex">
  <img class="col100 cover cover" src="https://www.gstatic.com/webp/gallery/1.sm.jpg" />
</section>
</div>

</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

为此,最好使用背景图像div,以保留图像尺寸。请在下面的代码段中找到我的background-image课程!我希望这会有所帮助。

.left{
  float:left;
}
.col100{
  width:100%; 
 }
.col33{
  width:33%;
}
.h30{
  height: 30vw;
 }
 .mright10{
  margin-right:10px;
 }
.bgred{
  background:red;
 }
 .bold{
  font-weight:bold;
 }
 .cover{
  object-fit: cover;
 }
.contain{
  object-fit: contain;
 }
.fill{
  object-fit: fill;
 }
 .flex{
  display:flex;
 }
 .background-image {
  background-image: url('https://www.gstatic.com/webp/gallery/1.sm.jpg');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
}
<div class="left col33 mright10">
<p class="left col100">Original Size</p>
<section class="col100 left h30 bgred">
  <img class="col100" src="https://www.gstatic.com/webp/gallery/1.sm.jpg" />
</section>
</div>

<div class="left col33">
<p class="left col100">contain</p>
<section class="col100 left h30 bgred flex">
  <img class="col100 cover contain" src="https://www.gstatic.com/webp/gallery/1.sm.jpg" />
</section>
</div>

<div class="left col33 mright10">
<p class="left col100">fill</p>
<section class="col100 left h30 bgred flex">
  <img class="col100 cover fill" src="https://www.gstatic.com/webp/gallery/1.sm.jpg" />
</section>
</div>

<div class="left col33">
<p class="left col100 bold">Cover - no longer stretched !</p>
<section class="col100 left h30 bgred flex background-image">
  
</section>
</div>