Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (20.3k points)
edited by

I want to show an image from a URL with a certain width and height even if it has a different size ratio. So I want to resize (maintaining the ratio) and then cut the image to the size I want.

I can resize with HTML img property and I can cut with background-image. 

How can I do both?

Example:

With img I can resize the image 200x150px:

<img 

    style="width: 200px; height: 150px;" 

    src="Your Image Url">

That gives me this:

<img style="width: 200px; height: 150px;" src="Your Image Url">

And with background-image, I can cut the image 200x100 pixels.

<div 

    style="background-image:

           url('Your Image Url'); 

    width:200px; 

    height:100px; 

    background-position:center;">&nbsp;</div>

Gives me:

<div style="background-image:url('Your Image Url'); width:200px; height:100px; background-position:center;">&nbsp;</div>

How can I do both? 

Resize the image and then cut it the size I want?

Has the size 800x600 pixels and I want to show as an image of 200x100 pixels

1 Answer

0 votes
by (40.7k points)

You can just use the combination of both methods for example:

    .crop {

        width: 200px;

        height: 150px;

        overflow: hidden;

    }

    .crop img {

        width: 400px;

        height: 300px;

        margin: -75px 0 0 -100px;

    }

    <div class="crop">

        <img src="Your Image Url" alt="Donald Duck">

    </div>

You can try using the negative margin to move the image around within the <div/>.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...