How to Override width and height HTML attributes with CSS

By  on  

One of the HTML elements that frequently comes into collision with CSS is the img element. As we learned in Request Metrics' Fixing Cumulative Layout Shift Problems on DavidWalshBlog article, providing image dimensions within the image tag will help to improve your website's score. But in a world where responsive design is king, we need CSS and HTML to work together.

Most responsive design style adjustments are done via max-width values, but when you provide a height value to your image, you can get a distorted image. The goal should always be a display images in relative dimensions. So how do we ensure the height attribute doesn't conflict with max-width values?

The answer is as easy as height: auto!

/* assuming any media query */
img {
  /* Ensure the image doesn't go offscreen */
  max-width: 500px;
  /* Ensure the image height is responsive regardless of HTML attribute */
  height: auto;
}

The dance to please users and search engines is always a fun balance. CSS and HTML were never meant to conflict but in some cases they do. Use this code to optimize for both users and search engines!

Recent Features

  • By
    Camera and Video Control with HTML5

    Client-side APIs on mobile and desktop devices are quickly providing the same APIs.  Of course our mobile devices got access to some of these APIs first, but those APIs are slowly making their way to the desktop.  One of those APIs is the getUserMedia API...

  • By
    Page Visibility API

    One event that's always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?

Incredible Demos

  • By
    Retrieve Your Gmail Emails Using PHP and IMAP

    Grabbing emails from your Gmail account using PHP is probably easier than you think. Armed with PHP and its IMAP extension, you can retrieve emails from your Gmail account in no time! Just for fun, I'll be using the MooTools Fx.Accordion plugin...

  • By
    MooTools Accordion: Mouseover Style

    Everyone loves the MooTools Accordion plugin but I get a lot of requests from readers asking me how to make each accordion item open when the user hovers over the item instead of making the user click. You have two options: hack the original plugin...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!