Bummer! You have been redirected as the page you requested could not be found.

Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Using CSS only, how would you increase the size of an image, while maintaining the aspect ratio?

Hey guys!

I'm trying to resize an image using only CSS (no HTML). I haven't found a good solution, so I've been using a workaround. Please review my code below:

p a img {
height: auto;
width: 1200px;
}

p a img {
height: 1200px;
width: auto;
}

The images were originally around 800px before I resized them. Any ideas on how to improve the code?

I know there has to be a better way to do this.

Best regards,

Andreaus

3 Answers

How about setting height and width in % as in height: 80%. When you adjust the size of the parent div, the size of the image will adjust automatically.

Edit: the answer above was how to make the image fluid based on the width of the browser. The answers below by others on just setting one of the dimension is for adjust the image in CSS to a fixed size, is probably more fitting to your question.

Thanks Mauri! That seemed to work well for the desktop view, now I'll just have to change the margins for the smaller screens.

Hi Andreaus,

I'm not sure if you are using both of those css rules together but the second one overrides the first one and so there's no need to have the first rule.

To resize an image in css while maintaining aspect ratio, you would either set the width or the height to some value. The browser will figure out what the other one needs to be to maintain the aspect ratio.

So something like:

img {
    width: 1200px;
}

This will resize the image to 1200px wide and the height will scale proportionally.

Can you state what your goal is? What is your native width and height and what size are you trying to make it on the page?

Thanks Jason! I didn't know that you could just specify the width to maintain the aspect ratio.

I've got it working now.

You're welcome.

The same thing works for height too if you leave off the width and set the height only. It's probably more common to set the width though.

Hi Andreaus,

If you specify the width property/value only, the height will adjust itself accordingly.

p a img {
     width: 1200px;
}

Hope this helps.

Edit: Jason beat me to it :)

Regards, Sam

Thanks samnabhan!