Home > other >  extract landscape image from any ratio in css
extract landscape image from any ratio in css

Time:12-29

Can anybody tell how to "extract" a landscape image in css from no matter what ratio the image has before? The Image should not be scaled but being cropped. The "new image" should contain the center of the inputted image.

CSS:

.doesNotWork{
    width:50%;
    height:50%;
    border: 1px solid rgb(34, 23, 187);
  /* in my opinion this div should be a square too and display the same content as the other one but a bit bigger to be 50% of the width of the screen*/
}

.worksAsExpected{
    width:250px;
    height:250px;
    border: 1px solid rgb(34, 23, 187);
}


.cover {
    width:100%;
    height:100%;
    border: 1px solid rgb(187, 23, 23);
    object-fit: cover;
}

HTML:

<div >
    <img src="https://www.w3schools.com/w3images/woods.jpg" alt="test" />
</div>
<div >
    <img src="https://www.w3schools.com/w3images/woods.jpg" alt="test" />
</div>

I made a Codepen that exactly display the issue. Hope someone can help me with this:

https://codepen.io/su-koch/pen/JjrMqYd

CodePudding user response:

The first element in the given code has 50% width. This will be 50% of the parent element, in this case body which has taken in viewport width.

The same idea applies to height. It is 50% of the height of the parent. It has no relationship to width.

If you want the two to be linked you can on modern browsers use aspect-ratio. Set width 50% as now, and set aspect-ratio: 1 / 1;

This will give you a square.

  • Related