What is the correct way to make an image adjust to changes in a browser's size?

I'm in a bit of a quandary: How can I ensure that an image resizes properly based on viewport size?

So, here's the challenge - I have an image that is 400 pixels wide and 400 pixels tall. My aim is for it to occupy only 90% of the width of the viewport (90vw) upon resizing the browser window. Currently, this is the CSS code I am using:

img {
  width: 400px;
  height: 400px;
}

@media screen and (max-width: 400px) {
  img {
    width: 90vw;
    height: 90vh;
  }
}

The hitch I've run into is that the image doesn't seem to adjust at all with this current setup.

If I replace width with max-width, only the width changes, leaving me with a distorted elliptical image due to the unadjusted height.

Is there a simple solution to rectify my issue?

Answer №1

To prevent distortion when styling an image with CSS, it's best to set either the height or width and allow the other dimension to adjust automatically. For example, if your image is sized at 400px × 400px, you can use the following code:

#myImg {
  width: 400px;
  height: auto;
}
@media (max-width: 440px) {
  #myImg { 
    width: 90vw;
  }
}

/* optional, for centering */
#myImg {      
  display: block;
  margin: 0 auto;
}
<img src="http://via.placeholder.com/400x400" id="myImg">

You can experiment with this setup by visiting this link. The choice of using 440px in the media query was made to avoid a sudden drop in size from 400px to 360px across the 400px device width threshold. Feel free to customize this value based on your needs.

Answer №2

Consider using the object fit property for better control over image resizing.

img {
  width: 400px;
  height: 400px;
  object-fit: cover;
}

@media screen and (max-width: 400px) {
  img {
    width: 90vw;
    height: 90vh;
  }
}

Alternatively, you can use a background image approach for improved browser compatibility.

Answer №3

To achieve this, you will have to define two separate @media queries - one for adjusting the layout horizontally and another for making vertical adjustments. Both of these queries should be set at a maximum width and height of 400px. In the horizontal adjustment query, only utilize the width property, while in the vertical adjustment query, focus solely on the height property:

body {margin: 0}

img {
  display: block; /* removes bottom margin/whitespace */
}

@media (max-width: 400px) {
  img {width: 90%}
}

@media (max-height: 400px) {
  img {height: 90vh}
}
<img src="http://placehold.it/400x400" alt="">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered while scrolling with a fixed position

I am currently in the process of developing a carousel slider that resembles what we see on Android devices. The main challenge I am facing at this early stage is applying the CSS property position: fixed; only horizontally, as vertical scrolling will be n ...

Is there a way to encase numerous <tbody> elements together?

My table design has specific css requirements where I am using multiple <tbody> tags. It looks like this: Example with multiple tbody tags However, I also need a wrapper for the multiple tbody tags (similar to a common tbody parent) that can be scr ...

Animating rows in the grid auto property

I am working with a basic css grid that contains X number of grid items. These grid items can vary in size and I need to implement an expander feature. The goal is to initially display only a certain number of rows, but upon clicking a button, the grid wil ...

What is the best way to navigate back to the top of the page once a link has been clicked?

One issue I'm facing is that whenever I click on a link in NextJS, it directs me to the middle of the page: <Link href={`/products/${id}`} key={id}> <a> {/* other components */} </a> </Link> I believe the problem l ...

align items center with respect to my central element

Describing my issue might be a bit complex, but I'll give it a shot. I'm working on a website and have 3 div elements in the header for my navigation bar (burger menu / logo / social networks). I've used flex display with justify-content: be ...

Problem with padding in Firefox when using jQuery's css() methodInconsistent behavior with padding property in

It has come to my attention that Firefox (specifically v19.0.2) is encountering an issue with the jQuery css() function when attempting to retrieve an element's padding. While using .css('padding-left') seems to be a workaround, it would be ...

Explore a variety of themes for the antd design token

Is there a way to access the text color of both the default and dark themes using design tokens? I am looking for a method to seamlessly switch between the two color schemes based on specific conditions, without having to change the entire theme. For ins ...

There seems to be an issue with the CSS file linking properly within an Express application

Every time I run my app.js file, the index.html file is displayed. However, when I inspect the page, I notice that the CSS changes are not taking effect. Strangely, if I open the HTML file using a live server, the CSS changes are visible. Can someone exp ...

Showing information to several classes using JavaScript

I am currently developing a "Gamebook Engine" that enables users to set a custom username. The user name is extracted from an input element with the id="setUserNameInput" and stored using the function setUserName(). It is then displayed or loaded into an e ...

Guide to generating customized CSS styles on-the-fly in Vue (similar to Angular's dynamic styling capabilities)

When working with Angular, we have the capability to dynamically set CSS properties. For example: <style ng-if="color"> .theme-color { color: {{color}}; } .theme-background-color { background-color: {{color}}; } .theme-border-color { border-color: { ...

showing divs in a compact layout on smaller screens using Bootstrap 5

Is there a way to set up two div elements so that they are displayed as blocks on small screens and inline on large screens? I also need their width to span 100% of the screen. ...

Incorporating additional value attributes without replacing the existing ones

Is there a way to add a value attribute through jQuery without removing the old attribute, similar to how addClass works? I have 7 input fields that are being typed in, and I need to combine them into one word and pass it to another input field. When I try ...

Can the loaded image from the css sprite be displayed on the screen?

My webpage is designed to load two images from a CSS sprite using the following code: <html> <head> <link rel="stylesheet" type="text/css" href="stylesheet.css"> </head> <body> <div class="arrow low"></div> ...

How can you quickly navigate to the top of the page before clicking on a link in the same window/tab?

Could someone assist me with a coding issue I am facing? I would like to be able to go to the top of the page when clicking on a link and have the link open in the same tab. I attempted to implement this functionality using the following code, however, I ...

What is the best way to resize my hamburger menu and achieve a flawlessly circular border for it?

I've been struggling to reduce the size of my hamburger menu (both height and width) for some time now. I managed to make it a bit smaller, but I can't seem to figure out how to shrink it further. Additionally, I'm having trouble creating a ...

Optimizing Window Width with React.js and CSS

I'm currently in the process of building a responsive website with react. I am utilizing CSS stylesheets for styling and have used @media queries to ensure responsiveness. However, I've encountered an issue while testing in Chrome where the elem ...

Use jQuery to replace this color with that color in CSS every time it appears

I have numerous div elements, some with a background-color: #aaa, others with font color: #aaa, and some with border-color: #aaa. There are also divs with various other colors. I am looking to update these colors (#aaa) to #ccc throughout the CSS. While ...

VueJS component fails to remain anchored at the bottom of the page while scrolling

I am currently using a <md-progress-bar> component in my VueJS application, and I am trying to make it stay fixed at the bottom of the screen when I scroll. I have attempted to use the styles position: fixed;, absolute, and relative, but none of them ...

CSS query: How to eliminate the extra space at the top of a webpage?

How can I eliminate the gray area visible here: The padding in style.css is currently set to: padding: 0; I have attempted to modify this by changing the following: #page { margin-top: 0; } I have tried variations such as: #page { margin-top: 5px !im ...

AngularJS: How to automatically scroll to the bottom of a div

I cannot seem to scroll to the last message in my chat window. var app=angular.module('myApp', ['ngMaterial'] ); app.controller('ChatCtrl', function($window, $anchorScroll){ var self = this; self.messageWindowHeight = p ...