I am a little new to CSS. I am trying to apply to an image a 16:9 ratio.
I have seen both the object-fit
and aspect-ration
properties.
Do I need the object-fit
property if I just use the aspect-ratio: 16/9
property ?
I did read an article New aspect-ratio CSS property and the writer uses both.
Can someone please clarify this?
CodePudding user response:
Here's an example of why you would want to combine aspect-ratio
with object-fit
: So your image doesn't get stretched.
You can control the composition within the newly specified aspect ratio using object-fit
and object-position
.
img {
border: 2px solid red;
width: 190px;
}
label {
display: inline-block;
}
span {
display: block;
font-size: 13px;
text-align: center;
}
.ar {
aspect-ratio: 16/9;
}
.of {
object-fit: cover;
}
<label>
<img src="https://www.englishclub.com/images/kids/shapes-615.png" />
<span>no aspect-ratio or object-fit</span>
</label>
<label>
<img src="https://www.englishclub.com/images/kids/shapes-615.png" />
<span>aspect-ratio: 16/9</span>
</label>
<label>
<img src="https://www.englishclub.com/images/kids/shapes-615.png" />
<span>aspect-ratio: 16/9 object-fit: cover</span>
</label>