2

CSS 对象适合位置fillcontain正在工作,但cover工作方式类似fill. 无论图像有多少部分,它都必须在不拉伸的情况下填充 div cover。我将 div 设置为flex并应用于object fit positiondiv 内部的图像。为什么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>

4

1 回答 1

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>

于 2018-06-18T09:01:32.353 回答