Zach’s ugly mug (his face)

Zach Leatherman

Barebones CSS for Fluid Images

January 30, 2021 #2 Popular Inspired by a tweet.

A few days back CarolSaysThings’s AvatarCarolSaysThings posed what I expected to be a simple question until I started to question what I already knew. Carol had some image markup (generated by Eleventy Image) and was asking the best way to make the image fluid (match the width of its container). I knew I understood this well enough to use it in my own work but I started to realize that perhaps I didn’t know this topic well enough to teach it so I dove in a little deeper.

Primary goal: I want to test width: 100% versus max-width: 100% and how those interact with [width][height] and srcset attributes.

Now, my usual take was to pop some width: 100% CSS on that thing and call it a day. width: 100% CSS forces the image to fill up the width of the container. This overrides any [width] attribute you have set. This has the downside that the image can outgrow it’s own dimensions and can appear blurry.

Each case below uses a 200×200 image in both a 150px container (to shrink) and a 300px container (to grow).

width: 100%

Without [width][height]

The sample Nebula Image from Unsplash on the Eleventy Image docs
The sample Nebula Image from Unsplash on the Eleventy Image docs

Using [width][height]

The sample Nebula Image from Unsplash on the Eleventy Image docs
The sample Nebula Image from Unsplash on the Eleventy Image docs

The 100% in max-width refers to the container dimensions. Sometimes the [width] attribute will be smaller than this container, which means the image will not always be full width. Practically speaking, the image will never grow larger than its own internal or intrinsic dimensions.

Another way to think about this, the image width can range between 0 and [width], depending on the container size.

Editors note: the above section had a pretty glaring error and was corrected thanks to @CarolSaysThings, @HarryMoore2409, and @nhoizey! Sorry about that, y’all.

max-width: 100%

Without [width][height]

The sample Nebula Image from Unsplash on the Eleventy Image docs
The sample Nebula Image from Unsplash on the Eleventy Image docs

Using [width][height]

The sample Nebula Image from Unsplash on the Eleventy Image docs
The sample Nebula Image from Unsplash on the Eleventy Image docs

Let’s use srcset to add another eligible image width (now 200px and 400px) and see what happens. Spoiler alert: no surprises here! 🎉

srcset and width: 100%

Without [width][height]

The sample Nebula Image from Unsplash on the Eleventy Image docs
The sample Nebula Image from Unsplash on the Eleventy Image docs

Using [width][height]

The sample Nebula Image from Unsplash on the Eleventy Image docs
The sample Nebula Image from Unsplash on the Eleventy Image docs

Keeping our two eligible image widths in play (200px and 400px) let’s swap to use max-width: 100%.

srcset and max-width: 100%

Without [width][height]

The sample Nebula Image from Unsplash on the Eleventy Image docs
The sample Nebula Image from Unsplash on the Eleventy Image docs

Using [width][height]

The sample Nebula Image from Unsplash on the Eleventy Image docs
The sample Nebula Image from Unsplash on the Eleventy Image docs

This is where the rubber finally meets the road. For me, the above test was the most surprising part of the research—and why a deeper analysis of this perhaps introductory topic was worthwhile (for me).

When I traditionally used width: 100% it bulldozed the [width] attribute. But a strict max-width: 100% now competes with the [width] attribute. One easy solution here is to add width: auto to pair with our max-width: 100% CSS. That looks like this:

srcset and max-width: 100%

Using [width][height] and width: auto

The sample Nebula Image from Unsplash on the Eleventy Image docs
The sample Nebula Image from Unsplash on the Eleventy Image docs

When Eleventy Image generates markup for more than one size, the <img> element uses the lowest size/quality source. But this behavior has me thinking that when srcset is in play it should use the largest dimensions for the [width] and [height] attributes. I wonder what y’all think about that? Practically, it would look like this:

srcset and max-width: 100%

Using [width="400"][height="400"]

The sample Nebula Image from Unsplash on the Eleventy Image docs
The sample Nebula Image from Unsplash on the Eleventy Image docs

This makes max-width: 100% a bit more predictable, as the rendered size now matches the behavior when [width][height] are not included or when width: auto was left off. The maximum width now correctly matches the intrinsic width of the largest image in our srcset list.

February 24, 2021 Update: Eleventy Image v0.8.0 was released with the above [width][height] attribute optimization.

Again—practically I would recommend to pair max-width: 100% with width: auto to fix this in the easiest way but this might help avoid some confusion for some folks that aren’t aware of this.

Conclusions (aka TL;DR) #

  • All of these approaches operate the same when the container is smaller than the image.
  • Using width: 100% can give you some blurry images if you’re not careful with your container sizes.
  • Using max-width: 100% constrains the image to the container, but be careful when you use this with srcset—it may cap smaller than you want when using [width]! Pair with width: auto to fix this.
  • But perhaps esoterically I’m walking away with this remaining question: when you have multiple image sizes listed in a srcset list, which dimensions do you use for the [width] and [height] attributes? I kinda want to use the largest one—any obvious downsides to that?

Copy and Paste #

Writing this blog post has swayed me to part from my width: 100% ways! I think this is what my boilerplate will be moving forward (it renders like the above example using width: auto):

img {
max-width: 100%;
}
img[width] {
width: auto; /* Defer to max-width */
}
img[width][height] {
height: auto; /* Preserve aspect ratio */
}

/* Let SVG scale without boundaries */
img[src$=".svg"] {
width: 100%;
height: auto;
max-width: none;
}

February 24, 2021 Update: Chris Coyier posted a great follow up to this post on CSS Tricks with some super valuable extra information about how srcset affects rendered image dimensions.

Zach’s ugly mug (his face)

Zach is a builder for the web with Netlify. He’s currently fixated on web fonts and static site generators. His public speaking résumé includes talks in eight different countries at events like Beyond Tellerrand, Smashing Conference, CSSConf, and The White House. He is an emeritus of Filament Group, NEJS CONF, and still helps out with NebraskaJS. Read more about Zach »

Previous
Jamstack 101: Getting Started with Eleventy
Next
Don’t Shut Down Your Business! Instead Use Eleventy Image

19 Retweets

PatidouNicolas HoizeyFynn BeckerMichael StramelBecky LingafelterFabrice Gangler 🔗Lee PearsonMohammad ArifDan DenneyMattSaravanaStephanie EcklesAndy BellMatthias OttJens GrochtdreisRob DodsonCarol 🌻Sami KeijonenMWDelaney
120 Likes
Harry MooreKyle HallDemon NewmanPeter AntoniusCarol 🌻Nicolas HoizeyÁngel GuerraNicolas HoizeyGaël PoupardRob DodsonAdrian CastellanosAbdessalammason conkrightParkerBond usePrivilege(stopRacism)U+2B0Bx3Keith PurtellEric WallaceDave RupertEthan MarcotteJeremy WagnerFynn BeckerMikaelaAgility CMSMaëligGaël PoupardSteven ParkJeremy Van StaalduineDanny de VriesJohn JordanMatt SecoskeStefan RüschenbergSamrat GuptaNatalie ChinUsama Iqbal (گوگل)Bruno CarvalhoGautam Kumarscottunderwood.meVladislav Shkodinrizwana akmal khanpozole con repolloKevin McLoughlinNeoDarqueEric CheungrazhMarisa DeMeglioMichael StramelIago BarreiroMarcamillianCarles MuiñosBrett JankordGraham BancroftMarco useCauseAndEffect()Ilya StreltsynBecky LingafelterOsmelPeter AntoniusandeySlightly WarpedParkerBond usePrivilege(stopRacism)Miguel Ángel DuránNikita Voloboevjordi colomereusebioJessmonchowizThis Dot LabsLee PearsonJody DonettiElle Townsend🌸Arthur MeloAna RodriguesEric BaileydevBrett EvansAntonio Laguna ツAurora Johansen-WardigoTodd 🦞AllisonMatthias WestonStephen Scott 💙💚Jewwy QadriRattleknife DesignGreg HowleyFlorian GeierstangerShane DuffIvan NikolićJake DohmLucas HardisonDavid EastJacob LeechStephanie EcklesRachel LeggettMichelle BarkerJo DoddRick BergfalkAndy BellCorey MegownJohn F Croston IIIYomar Miranda ⚡︎Matthew Dean™ShawI am Wes Wilson 👋Jens GrochtdreisAdam Di MarioMark McLaughlinEthan MarcotteMatthias OttMWDelaneyDave 🧱Marc Littlemore 🤖Jesse HeadySteven PriceBryson GilbertCarol 🌻GlennDyour favorite JackiePhilippRob DodsonEric WallaceTanner DolbyPatrick Connors
33 Replies
  1. Demon Newman

    Demon Newman @thedamon #

    So if the image is fluid and 50% width.. do I put the intrinsic width (which I do not know) or what? Typically width is for display so this guideline deeply messes with me (and also changes image[width] bit in your snippet)

  2. Zach Leatherman

    Zach Leatherman @zachleat #

    Yeah definitely add them, they’re an important performance optimization to establish the image’s aspect ratio to prevent layout shift!

  3. Demon Newman

    Demon Newman @thedamon #

    I never thought of tagging styles to whether the height/width attribute is set! Very cool. Do you have thoughts on lighthouse yelling about missing width attributes though? Most of our images are sized with css and also have sizes attribute set so... do I ignore that?

  4. Nicolas Hoizey

    Nicolas Hoizey @nhoizey #

    You’re welcome! 👍

  5. Nicolas Hoizey

    Nicolas Hoizey @nhoizey #

    Currently reading your article, I'm really surprised by "The 100% in max-width refers to the image’s dimensions". IMHO, these 100% refer to the container width.

  6. Harry Moore

    Harry Moore @HarryMoore2409 #

    You say “The 100% in max-width refers to the image’s dimensions”, is that true? I thought % in CSS was based on the parent element size

  7. Zach Leatherman

    Zach Leatherman @zachleat #

    My hunch is that using these test cases to analyze which image is selected in srcset might not be the best thing—I’d need to learn more about how the browser coalesces multiple requests of differing sizes. Note that the URLs for the images are the same on the left/right

  8. Senthil P

    Senthil P @senthil_hi #

    Correct. But a 400px image downloaded for a 150px container seems to be expensive, right?

  9. Zach Leatherman

    Zach Leatherman @zachleat #

    This is what I expect to see:

  10. Dohány Tamás

    Dohány Tamás @iamdtms #

    Aspect-ratio extension would be nice to have! ;)

  11. Senthil P

    Senthil P @senthil_hi #

    Great post. In your demo (SRCSET AND MAX-WIDTH: 100% & Using [width="400"][height="400"]) for the small container, I still see the 400px image rendered in the browser. We should see the 200px image, right? Link zachleat.com/web/fluid-imag…

  12. Andy Bell

    Andy Bell @piccalilli_ #

    same tbh

  13. Eric Bailey

    Eric Bailey @ericwbailey #

    my_career.txt

  14. Zach Leatherman

    Zach Leatherman @zachleat #

    @ericwbailey told me “the marvel is not that the bear dances well, but that the bear dances at all”

  15. Andy Bell

    Andy Bell @piccalilli_ #

    [blushes] It’s actually 3 squirrels stood on top of each other, in a long coat.

  16. Ivan Nikolić

    Ivan Nikolić @niksy #

    Yes, I was refering to that, basically max-width and height combo! Your solution seems like more explicit and more resilient implementation 😄

  17. Zach Leatherman

    Zach Leatherman @zachleat #

    Awesome, thanks!

  18. Rob Dodson

    Rob Dodson @rob_dodson #

    Maybe also worth mentioning that we inline our css so the column width and img max-width styles are in place very early.

  19. Zach Leatherman

    Zach Leatherman @zachleat #

    Of course! Your CSS reset is incredible, btw—well maintained!

  20. Rob Dodson

    Rob Dodson @rob_dodson #

    Btw Jen Simmons has a really good video on this that I found super helpful. youtu.be/4-d_SoCHeWE

  21. Rob Dodson

    Rob Dodson @rob_dodson #

    Yeah we combine it with srcset and on smaller screens it seems to download the correct smaller image

  22. Andy Bell

    Andy Bell @piccalilli_ #

    This is bloody excellent. Permission to update the modern CSS reset with your findings?

  23. Rob Dodson

    Rob Dodson @rob_dodson #

    Because we know our max column size when someone uploads an image to our cdn we give them back a snippet to use which has the width and height attributes prefilled and it has constrained them to our max column size.

  24. Zach Leatherman

    Zach Leatherman @zachleat #

    oh interesting—so a bit of evidence that it’s okay to use larger width/height attributes?

  25. Rob Dodson

    Rob Dodson @rob_dodson #

    Oh good write up! I think we inadvertently avoided the last issue because the value we use for the width attribute is always the width of the original image.

  26. Zach Leatherman

    Zach Leatherman @zachleat #

    yeah I agree that’s weird 😅

  27. Carol 🌻

    Carol 🌻 @CarolSaysThings #

    and that when you say max-width: 100% it relates to the image’s width but when you say width: 100% it relates to the image’s container’s width 🤔 The more you know 💫

  28. Carol 🌻

    Carol 🌻 @CarolSaysThings #

    This is such a great explanation, thanks for writing it! 🙌🏼 I started my site rebuild layer by layer so I could learn things, and it’s definitely working 😅 I think 2 things surprised me from the off: that I needed CSS at all to get the picture element to be responsive; (+)

  29. Zach Leatherman

    Zach Leatherman @zachleat #

    Mine is a tiny bit different but yes! zachleat.com/web/fluid-imag…

  30. Cristovao Verstraeten

    Cristovao Verstraeten @apleasantview #

    Mint post! I'm convinced ... I think 😅

  31. Ivan Nikolić

    Ivan Nikolić @niksy #

    It seems like I’ve been doing similar thig for quite some time, it’s just that it was more like trial and error thing! 😅 github.com/niksy/rational… Thanks for the writeup!

  32. Zach Leatherman

    Zach Leatherman @zachleat #

    I was basically this same thing until about 2 days ago 😅 But I wrote it up so you can just read it and don’t have to write a bunch of tests to learn how it works! 🏆

  33. MWDelaney

    MWDelaney @MichaelWDelaney #

    I am so lazy. I figure whatever CSS framework I'm using has solved this for me. I'm turning in my developer card.

    73 Mentions
    1. \\ uto-usui //

      \\ uto-usui // @uto_ao #

      🖼 FLUID IMAGES img { max-width: 100%; } img[width] { width: auto; } img[width][height] { height: auto; } img[src$=".svg"] { width: 100%; height: auto; max-width: none; } zachleat.com/web/fluid-imag…

    2. @simounet@mastodon.simounet.net

      @simounet@mastodon.simounet.net @Simounet #

      Barebones CSS for Fluid Images // #CSS zachleat.com/web/fluid-imag…

    3. Julian

      Julian @julzmon #

      Barebones CSS for Fluid Images—zachleat.com zachleat.com/web/fluid-imag…

    4. tipsxd.com #

    5. tipsxd.com #

    6. tipsxd.com #

    7. worldtech.news #

    8. techupd.com #

    9. techupd.com #

    10. techupd.com #

    11. technologynews.biz #

    12. htmltreehouse.com #

    13. techalertnews.com #

    14. pixallus.com #

    15. 711web.com #

    16. www.webwaycanada.ca #

    17. softwaremile.com #

      Show original post Zach takes a look at some fundamental HTML+CSS usage for fluid, responsive images. Most of it, I’d say, is what you’d expect, but things get weird when srcset gets involved. I poked my way through, and in addition to the weird thing Zach noted, wanted to add one more thing. Let’… Truncated

    18. www.scoop.it #

    19. 34.86.126.177 #

    20. 34.86.126.177 #

    21. 34.86.126.177 #

    22. wpguynews.com #

    23. wpguynews.com #

    24. wpguynews.com #

    25. admin https://h4host.com/index.php/author/admin/ #

      Zach takes a look at some fundamental HTML+CSS usage for fluid, responsive images. Most of it, I’d say, is what you’d expect, but things get weird when srcset gets involved. I poked my way through, and in addition to the weird thing Zach noted, wanted to add one more thing. Let’… Truncated

    26. wpnewshub.com #

    27. dztechno.com #

    28. dztechno.com #

    29. www.digitasbuzz.in #

    30. ModeratorGT https://gotutoral.com/author/admin/ #

      A few days back CarolSaysThings posed what I expected to be a simple question until I started to question what I already knew. Carol had some image markup (generated by Eleventy Image) and was asking the best way to make the image fluid (match the width of its container). I knew … Truncated

    31. ModeratorGT https://gotutoral.com/author/admin/ #

      A few days back CarolSaysThings posed what I expected to be a simple question until I started to question what I already knew. Carol had some image markup (generated by Eleventy Image) and was asking the best way to make the image fluid (match the width of its container). I knew … Truncated

    32. marketingsolution.com.au #

      Show original post Barebones CSS for Fluid Images February 19, 2021 Web Development No Comments Zach takes a look at some fundamental HTML+CSS usage for fluid, responsive images. Most of it, I’d say, is what you’d expect, but things get weird when srcset gets involved. I poked m… Truncated

    33. docuneedsph.com #

    34. www.newsgosspis.com #

    35. www.newsgosspis.com #

    36. www.newsgosspis.com #

    37. techfans.co.uk #

    38. Tech Team https://711web.com/author/admin711/ #

      A few days back CarolSaysThings posed what I expected to be a simple question until I started to question what I already knew. Carol had some image markup (generated by Eleventy Image) and was asking the best way to make the image fluid (match the width of its container). I knew … Truncated

    39. pikopong.com #

    40. www.webmastersgallery.com #

    41. codedigger.ca #

      A few days back CarolSaysThings posed what I expected to be a simple question until I started to question what I already knew. Carol had some image markup (generated by Eleventy Image) and was asking the best way to make the image fluid (match the width of its container). I knew … Truncated

    42. codedigger.ca #

      A few days back CarolSaysThings posed what I expected to be a simple question until I started to question what I already knew. Carol had some image markup (generated by Eleventy Image) and was asking the best way to make the image fluid (match the width of its container). I knew … Truncated

    43. techylegends.com #

      Zach takes a look at some fundamental HTML+CSS usage for fluid, responsive images. Most of it, I’d say, is what you’d expect, but things get weird when srcset gets involved. I poked my way through, and in addition to the weird thing Zach noted, wanted to add one more thing. Let’… Truncated

    44. CSS Basics

      CSS Basics @cssbasics #

      Barebones CSS for Fluid Images, by @zachleat zachleat.com/web/fluid-imag…

    45. richard.blog #

    46. assuagetech.net #

    47. docuneedsph.com #

    48. Tech Team https://711web.com/author/admin711/ #

      Bootstrap 5 CheatSheet – This interactive reference will help you navigate the latest version of Twitter’s CSS framework. Make Animated Content Placeholders with HTML and CSS – Add user-friendly placeholders with this tutorial. Why Is Focusing on Long-Term Goals So Difficult?… Truncated

    49. speckyboy.com #

    50. Front-End Front

      Front-End Front @frontendfront #

      Barebones CSS for Fluid Images zachleat.com/web/fluid-imag…

    51. Joulse

      Joulse @Joulse_ #

      Barebones CSS for Fluid Images zachleat.com/web/fluid-imag…

    52. Free Frontend

      Free Frontend @FreeFrontend #

      Barebones #CSS for Fluid Images zachleat.com/web/fluid-imag…

    53. Andy

      Andy @DTAndyB #

      Barebones CSS for Fluid Images—zachleat.com zachleat.com/web/fluid-imag… via @instapaper

    54. Speckyboy

      Speckyboy @speckyboy #

      Barebones #CSS for Fluid Images zachleat.com/web/fluid-imag…

    55. uiux.design.blog #

    56. Pinboard Popular

      Pinboard Popular @pinboard_pop #

      Barebones CSS for Fluid Images—zachleat.com zachleat.com/web/fluid-imag…

    57. Trevor Pierce

      Trevor Pierce @1Copenut #

      Barebones CSS for Fluid Images—zachleat.com zachleat.com/web/fluid-imag…

    58. docuneedsph.com #

    59. David Bisset

      David Bisset @dimensionmedia #

      Barebones #CSS for fluid images (via @zachleat) zachleat.com/web/fluid-imag…

    60. reddits.contractwebsites.com #

      submitted by /u/speckz [link] [comments]

    61. reddits.contractwebsites.com #

      submitted by /u/speckz [link] [comments]

    62. Pablo Lara H

      Pablo Lara H @pablolarah #

      Barebones Css For Fluid Images by Zach Leatherman @zachleat #css #image #webdev #eleventy zachleat.com/web/fluid-imag…

    63. www.lireo.com #

    64. tympanus.net #

    65. admin https://h4host.com/index.php/author/admin/ #

      Inspirational Website of the Week: CCNCN – Saison 2021 A fresh design with great typography and a daring, addicting click interaction concept. Our pick this week. Get inspired Our Sponsor Blockchain domains are owned, not rented Blockchain domains are stored by their owners i… Truncated

    66. Chris Heilmann

      Chris Heilmann @codepo8 #

      👉🏻 “Barebones CSS for Fluid Images” 🔗 zachleat.com/web/fluid-imag…

    67. Inspirational Website of the Week: CCNCN – Saison 2021 A fresh design with great typography and a daring, addicting click interaction concept. Our pick this week. Get inspired Our Sponsor Blockchain domains are owned, not rented Blockchain domains are stored by their owners i… Truncated

    68. dailydevlinks.

      dailydevlinks. @dailydevlinks #

      📝 Barebones CSS for Fluid Images 🔗 zachleat.com/web/fluid-imag… #html #css #javascript #webdev

    69. Веб-стандарты

      Веб-стандарты @webstandards_ru #

      Минимальные стили для адаптивных изображений. Зак Лезерман изучает поведение картинок с различными комбинациями свойств width, max-width и атрибутов width, height и srcset. zachleat.com/web/fluid-imag…

    70. Pablo Lara H

      Pablo Lara H @pablolarah #

      Barebones Css For Fluid Images by Zach Leatherman @zachleat #css #webdev #images #width zachleat.com/web/fluid-imag…

    71. Ринат Валиуллов (хи/хим)

      Ринат Валиуллов (хи/хим) @4rontender #

      👏

    72. Mattia Astorino

      Mattia Astorino @equinusocio #

      Intersting approach. 🤔 zachleat.com/web/fluid-imag…

    73. Alvin A. https://www.alvinashcraft.com/author/admin/ #

      Top Links TWC9: Windows Terminal 1.6 Preview, Python in VS Code, Pulumi, and more! | This Week On Channel 9 (Christina Warren) Transactions in Azure Cosmos DB with the .NET SDK (Leonard Lobel) How to achieve style inheritance with Blazor CSS isolation (Dave Brock) WinUI 3.0 M… Truncated