uSeRnAmEhAhAhAhAhA
uSeRnAmEhAhAhAhAhA

Reputation: 2587

How do I retain a Photo's Aspect Ratio using only HTML and CSS?

I'm a little slow to adopt the Responsive Design thing, but I understand how it's done. There's just one thing I don't understand. And for some reason, I don't ever remember having this problem in all the 10 years I've been making websites.

I have a big photo that is about 1920px X 1080px. I don't wanna cut it down cause I know people browse the web on much bigger screens. The problem I am facing right now is that this photo is ah centred on the page horizontally (just beneath the main navigation on the top of the page), and even though the rest of my site scales up and down as it should, the photo loses its aspect ratio as the window size changes/gets smaller/gets larger.

How do I ensure that the image retains its aspect ration as the site scales to different resolutions/sizes?

I would prefer a non-javascript solution since one of the main requirements of this particular site is a JavaScript-free site. Otherwise, I would just do some calculations and scale the image myself.

Upvotes: 1

Views: 73

Answers (3)

Barnee
Barnee

Reputation: 3399

You must fix either the height or width of the image for it to scale with the correct aspect ratio.Images are inline-block elements and thus we can set their dimensions.

Try:

img {
    width: 100%;
    height: auto;
}

Here's an example. Try resizing the window, or the canvas.

Upvotes: 3

Suraj Rawat
Suraj Rawat

Reputation: 3763

Let the browser or your device (mobile,computer screen) to calculate the image size

img {
width: 100%;
height: auto;
}

Upvotes: 0

demonofthemist
demonofthemist

Reputation: 4199

You need to give only width to your image & give a max-width so it will not exceed the screen port. Height will get automatically adjusted as per aspect ratio.

img {
    width: 100%;
    max-width: 100%;
    height: auto;
}

Upvotes: 1

Related Questions