The CSS Mindset

Ah yes, CSS. Hardly a week passes without it being the topic of a heated online discussion. It’s too hard. It’s too simple. It’s unpredictable. It’s outdated. Peter Griffin struggles with blinds dot gif.

I don’t know why CSS sparks so many different emotions in developers, but I have a hunch as to why it can sometimes seem illogical or frustrating: You need a certain mindset to write good CSS.

Now, you probably need a mindset for coding in general, but the declarative nature of CSS makes it particularly difficult to grasp, especially if you think about it in terms of a “traditional” programming language.

Other programming languages often work in controlled environments, like servers. They expect certain conditions to be true at all times, and can therefore be understood as concrete instructions as to how a program should execute.

CSS on the other hand works in a place that can never be fully controlled, so it has to be flexible by default. It’s less about “programming the appearance” and more about translating a design into a set of rules that communicate the intent behind it. Leave enough room, and the browser will do the heavy lifting for you.

For most people who write CSS professionally, the mindset just comes naturally after a while. Many developers have that “aha!” moment when things finally start to click. It’s not just about knowing all the technical details, it’s more about a general sense of the ideas behind the language.

I tried to list some of these here.

Everthing is a Rectangle

This seems obvious, given that the box model is probably one of the first things people learn about CSS. But picturing each DOM element as a box is crucial to understanding why things layout the way they do. Is it inline or block level? Is it a flex item? How will it grow/shrink/wrap in different contexts?

Open your devtools and hover over elements to see the boxes they’re drawing, or use a utility style like outline: 2px dotted hotpink to visualize its hidden boundaries.

The Cascade is your Friend

The Cascade - a scary concept, I know. Say “Cascade” three times in front of a mirror and somewhere, some unrelated styling will break.

While there are legitimate reasons to avoid the cascade, it doesn’t mean that it’s all bad. In fact, when used correctly, it can make your life a lot easier.

The important part is to know which styles belong on the global scope and which are better restricted to a component. It also helps to know the defaults that are passed down, to avoid declaring unnecessary rules.

As much as necessary, as little as possible

Aim to write the minimal amount of rules necessary to achieve a design. Fewer properties mean less inheritance, less restriction and less trouble with overrides down the line. Think about what your selector should essentially do, then try to express just that. There’s no point in declaring width: 100% on an element that’s already block-level. There’s no need to set position: relative if you don’t need a new stacking context.

Avoid unnecessary styles, and you avoid unintended consequences.

Shorthands have long effects

Some CSS features can be written in “shorthand” notation. This makes it possible to declare a bunch of related properties together. While this is handy, be aware that using the shorthand will also declare the default value for each property you don’t explicitly set. Writing background: white; will effectively result in all these properties being set:

background-color: white;
background-image: none;
background-position: 0% 0%;
background-size: auto auto;
background-repeat: repeat;
background-origin: padding-box;
background-clip: border-box;
background-attachment: scroll;

It’s better to be explicit. If you want to change the background color, use background-color.

Always Be Flexible

CSS deals with a large amount of unknown variables: screen size, dynamic content, device capabilities - the list goes on. If your styles are too narrow or restrictive, chances are one of these variables will trip you up. That’s why a key aspect in writing good CSS is to embrace its flexibility.

Your goal is to write a set of instructions that is comprehensive enough to describe what you want to achieve, yet flexible enough to let the browser figure out the how by itself. That’s why its usually best to avoid “magic numbers”.

Magic numbers are random hard values. Something like:

.thing {
width: 218px; /* why? */
}

Whenever you find yourself tapping the arrow key in your devtools, adjusting a pixel value to make something fit - that’s probably a magic number. These are rarely the solution to a CSS problem, because they restrict styles to a very specific usecase. If the constraints change, that number will be off.

Instead, think about what you actually want to achieve in that situation. Alignment? An aspect ratio? Distributing equal amounts of space? All of these have flexible solutions. In most cases, it’s better to define a rule for the intent, rather than hard-code the computed solution to it.

Context is Key

For many layout concepts it’s imperative to understand the relationship between elements and their container. Most components are sets of parent and child nodes. Styles applied to the parent can affect the descendants, which might make them ignore other rules. Flexbox, Grid and position:absolute are common sources of such errors.

When in doubt about a particular element behaving different than you’d want it to, look at the context it’s in. Chances are something in its ancestry is affecting it.

Content will change

Always be aware that what you see is just one UI state in a bigger spectrum. Instead of styling the thing on your screen, try to build a “blueprint” of the component. Then make sure that whatever you throw at it won’t break your styling.

Strings may be longer than intended or contain special characters, images might be missing or have weird dimensions. Displays may be very narrow or extremely wide. Those are all states you need to anticipate.

The number one mistake made by designers and developers alike is assuming that things will always look like they do in the static mockup. I can assure you, they will not.

Find Patterns and re-use them

When you set out to turn a design mockup into code, it’s often helpful to take inventory of the different patterns included first. Analyse each screen and take note of any concept that occurs more than one. It might be something small like a typographic style, or large like a certain layout pattern.

What can be abstracted? What’s unique? Thinking of pieces in a design as standalone things makes them easier to reason about, and helps to draw the boundaries between components.

Use consistent Names

A surprisingly large part of programming in general is coming up with good names for stuff. In CSS, it helps to stick to a convention. Naming schemes like BEM or SMACSS can be very helpful; but even if you don’t use them, stick to a certain vocabulary.


👉 DISCLAIMER
All these things were important for me to understand, but your personal experience as to what matters most might be different. Did you have another “aha” moment that made you understand CSS better? Let me know!

Further Reading

Webmentions

  1. Harry Roberts
    Oooh. I like this!
  2. Franco Scarpa
    Really liked this article by @mxbck. A set of guidelines to embrace the fluidity of the web and devices.
  3. Adam Norris
    😍 I can really relate to this! Great article!
  4. Manuel Matuzović
    Fantastic advice by Max. I'll share this post with every new class I teach.
  5. Marek Piechura
  6. Very nice article 👌
  7. Max Böck
    Thanks Mauricio!
  8. Juan
    "The number one mistake made by designers and developers alike is assuming that things will always look like they do in the static mockup. I can assure you, they will not." @mxbck I should put this on a t-shirt… and my email signature and my forehead… mxb.dev/blog/the-css-m…
  9. Joonas Kallunki
    "Then make sure that whatever you throw at it won’t break your styling. Strings may be longer than intended, images might be missing or have weird dimensions. Displays may be very narrow or extermely wide. Those are all states you need to anticipate." mxb.dev/blog/the-css-m…
  10. Juan
    That “a-ha” moment for me was when I opened up the Chrome Dev Tools the first time and saw how the various parts of the Box Model were highlighted. Same thing happened with Grid thanks to Firefox’s Grid Inspector.
  11. Koen Haesaerts
    You forgot tot mention specificity. CSS is all about specificity and cascading.
  12. @heydon@mastodon.social
    Specificity is a feature of the cascade.
  13. Andy Bell
    “Always be aware that what you see is just one UI state in a bigger spectrum. Instead of styling the thing on your screen, try to build a ‘blueprint’ of the component. Then make sure that whatever you throw at it won’t break your styling” mxb.dev/blog/the-css-m… Great by @mxbck
  14. This article would be worth the read if it only said "Shorthands have long effects" but there's a lot of other great information here too.
  15. Max Böck
    yeah there's lots of things I didn't mention. It's not really about the technical basis though, so I feel that's OK.
  16. Chi Señires 🇵🇭
    The only thing I don't really know how to do yet, which is listed in this article, is the consistent naming convention (from the known ones). But yes, agree to everything here! This is what helps me translate designs into code, and this mindset also helps me in designing 😆
  17. Reinhard Steudel
    If you have started with #CSS and you struggle, spend some time and read @mxbck 's article, it will really helps you - I promise 😊
  18. Dan Tonon
    @mxbck wrote this terrific article giving some great advice on how to get into the right mindset to write good CSS. If you are a beginner or you dread writing CSS, I'm sure applying these things will see some significant improvements in your CSS skills. mxb.dev/blog/the-css-m…
  19. Daniel Tan (he/they)
    This here is the single best sub-5-minute introductory article about understanding and writing CSS you will ever read. Subheadings include "Everything is a Rectangle", "The Cascade is your Friend" and "Context is Key". It all starts with the right mindset. https://t.co/SFw6WqnqZJ
  20. For Web
    Для вёрстки нужен особый образ мышления, утверждает Макс Бок и делится идеями, ставшими для него ключом к пониманию CSS → mxb.dev/blog/the-css-m…
  21. Andrey Pelykh
    "Avoid unnecessary styles, and you avoid unintended consequences." Nice point 👍
  22. Oleg
  23. Slade 🇺🇸⚓️
    Fwiw...I hugged each and every one of your commas.
  24. CSS {IRL}
    A wonderful post by @mxbck: The CSS Mindset mxb.dev/blog/the-css-m…
  25. James Steinbach
    Ever have a hard time getting your mind around "how CSS works?" Here's a great post that'll help: The CSS Mindset, by @mxbck mxb.dev/blog/the-css-m…
  26. Deborah Edwards-Onoro
    One of the hardest things for me when I started learning CSS: the cascade. #CSS
  27. Marko Čakarević
    The CSS Mindset | Max Böck - Frontend Web Developer #css #webdev mxb.dev/blog/the-css-m…
  28. JSter
    The CSS Mindset by @mxbck buff.ly/2XuiT0H
  29. Van
    👇
  30. KT Coope 🐝
    This is great. Lots of stuff about CSS just being impossibly hard seems to stem from just not sitting comfortably in the mindset you need to understand it.
  31. Fresh Frontend Links
  32. Mike Davidson
    How I feel (and look) three hours into vertically centering a div. mxb.dev/blog/the-css-m…
  33. CSS-Tricks
    The CSS Mindset mxb.dev/blog/the-css-m… "Everthing is a Rectangle" (That was mine in 2008! css-tricks.com/the-css-ah-ha-…) "The Cascade is your Friend" "Content will change"
  34. jemoraz
    The CSS Mindset | Max Böck - Frontend Web Developer mxb.dev/blog/the-css-m…, see more tweetedtimes.com/jemoraz?s=tnp
  35. Rio
  36. Micek
    The CSS Mindset | Max Böck - Frontend Web Developer mxb.dev/blog/the-css-m…
  37. Masahiro Harada
    CSSマインドセット。 ・すべては四角形 ・カスケードは友だち ・記述は必要最低限に ・ショートハンドの副作用 ・常にフレキシブルに ・コンテキストがカギ ・コンテンツは変化する ・パターンを探して再利用 ・一貫性ある命名規則 mxb.dev/blog/the-css-m…
  38. ダーシノ
    The CSS Mindset | Max Böck mxb.dev/blog/the-css-m… CSSの考え方: すべては長方形、最小限のプロパティ、マジックナンバー死すべしなど > I know. Say “Cascade” three times in front of a mirror and somewhere, some unrelated styling will break. カスケードは「正しく恐れる」のが重要だね!
  39. VizWorld™
  40. Ashish Bedekar
  41. Swiss UX/UI News
  42. Jake Neal
  43. Ximena Vila Ferral
    "You need a certain mindset to write good CSS." – @MicheBarks mxb.dev/blog/the-css-m…
  44. Refresh Detroit
    "CSS on the other hand works in a place that can never be fully controlled, so it has to be flexible by default." mxb.dev/blog/the-css-m…
  45. Keith Rogers
    Lots of great CSS advice here 👌
  46. ➡️ runtcpip.com
    I thought CSS was ridiculously hard as a child on Neopets...I'm still hanging out with the basics, but I find it a fun challenge. Getting into the higher concepts will probably make me temporarily mad lol
  47. Max Böck
    I also started out tweaking myspace themes and I had no idea what I was doing. It just takes a bit of patience I guess 😅
  48. Mario Hernandez
    Excellent post on CSS
  49. Luis A. Linan
    A good book you would recommend? I've tried a few, but they just didn't work for me.😞
  50. Carlo Bruno
    Adapting these mindsets will make CSS easier to work with! 🔥
  51. Carolyn
  52. Jacques Dupoux 🇭🇹
    I used to take being able to code css well for granted. Something any developer could do. But the more contact I’ve had with other developers I realized how coding good css is a real valuable skill set. mxb.dev/blog/the-css-m…
  53. Facundo Corradini
    Great article! I believe the issue goes even deeper. Imperative programming languages rely heavily on logical-mathematical intelligence, while HTML + CSS work more on the linguistics intelligence. So imo is not just a matter of difference mindsets, but different minds.
  54. IT Ninjas
    Nice, thanks for sharing man. Getting to a point where you are comfortably writing css on the fly accurately is so big to new devs, I struggled with it.
  55. Zoey Nguyen
    The CSS Mindset | Max Böck - Frontend Web Developer mxb.dev/blog/the-css-m…
  56. Jason Frazzano
    It’s mostly frustrating because of browser inconsistency. Example grid css on slots in a custom element. Mozilla won’t expand a grid cell if child width changes. But will animate grid cola and rows. No one ear will. Safari handles absolute position4slot chaotically &scales wtf.
  57. Jason Frazzano
    Like theoretically, grid plus subgrid lus slot could allow a flat dom. App_grid>slots[header,footer,main,left drawer,right drawer,apply subgrids to the slots and you just drop components into app and voila... but its implemented in an obstructionist manner
  58. Nicole Lambon
    Too true, but then again, CSS Junkie here! 🤪 The CSS Mindset by @mxbck buff.ly/2XuiT0H
  59. David Lewis
    Now take someone who doesn’t understand these basics and throw a massive CSS framework in the mix and it’s no wonder they hate it. It helps to be able to think like a designer and to write it from scratch. I don’t even use a reset or normalize.
  60. Beatrice Williams
    "CSS [...] works in a place that can never be fully controlled, so it has to be flexible by default." #webdev mxb.dev/blog/the-css-m…
  61. Adactio Links
    The CSS Mindset | Max Böck - Frontend Web Developer mxb.dev/blog/the-css-m…
  62. Emily
    "The Cascade - a scary concept, I know. Say “Cascade” three times in front of a mirror and somewhere, some unrelated styling will break." 😅😅 mxb.dev/blog/the-css-m…
  63. hellop2h
    Web Accessibility In Context Be Birchall explains why it’s so important to prioritize accessibility among teams and why there needs to be more awareness raised among developers. Read it The CSS Mindset An article by Max Böck where he lists the essential ideas behind CSS that help understand it better. Read it Our Sponsor The Future of WYSIWYG Divi takes WordPress to a whole new level with its incredibly advanced visual builder technology. You’ve never built a WordPress website like this before. Try it 404 Error Page Collection A collection of creative 404 page examples on Awwwards. Check it out The Future of Web Animation Sarah Drasner shows some bleeding edge animation techniques and gives an outlook on where animation is heading. Watch it Function-based Component API in Vue Evan You published an RFC for function-based component API in Vue inspired by React hooks. Check it out The Documentation Compendium Various templates and tips on writing high-quality documentation that people want to read. Read it Leveling Framework: a UI framework for three-dimensional space Oscar Gonzalez writes about the interesting concept of a level based view of the interface environment. Read it Pinker.js A standalone JavaScript library for rendering code/class diagrams on your web page. Check it out The Anatomy of a Jellyfish A creative and technical overview of Maru, an interactive audiovisual website made in collaboration with Plaid for their new album “Polymer”. By Isaac Cohen. Read it 3D Frame Illustrator A free tool for artists and designers to generate framed images in 3D. Check it out CSS Grid: No Nonsense Layouts A thorough tutorial by Austin Johnston on creating practical CSS layouts. Check it out This page is a truly naked, brutalist html quine. Leon Bambrick’s creative HTML quine experiment. Check it out freemium.cc A site that collects awesome tools for makers. Check it out Theme UI Build consistent, themeable React UIs based on design system constraints and design tokens. Check it out Variable Fonts | Compressa Juan Fuentes created this beautiful variable font experiment. Check it out Why Text Buttons Hurt Mobile Usability Read why using text buttons can be a problematic experience for the mobile user. Read it Free Font: Victor Mono Victor Mono is a programming font with semi-connected cursive italics and some symbol ligatures. Get it Growth Case Studies Tips and case studies by Growth.Design presented in a really cool way. Check it out Your first performance budget with Lighthouse Ire Aderinokun’s guide on how to enforce a performance budget with Lighthouse. Read it Breaking the physical limits of fonts Dale Weiler took an interesting challenge: with the fewest resources possible, render meaningful text. Read it CSS-only Animated Lantern A great demo by 7oot inspired by Fede Cook’s Dribbble shot. Check it out Pipe Dream for Laravel By giving Pipe Dream a minimum of input in form of a sketch/entity list, it will predict your application schema and feed it into a set of pipes. These pipes will generate all the files needed to get started with a new web project really quick. Check it out Collective #523 was written by Pedro Botelho and published on Codrops. Source: codedrops
  64. IT Tech BuZ
  65. Scott de Jonge
    As much as necessary, as little as possible. Fewer properties mean less inheritance, less restriction and less trouble with overrides down the line. mxb.dev/blog/the-css-m…
  66. Ale Mohamad ランダム
    “The CSS Mindset” by @mxbck mxb.dev/blog/the-css-m…
  67. Peeke Kuepers
    The 'everything is a square' bit helped me a lot at the time. Great article!
  68. bejo
  69. stay positive
    I’m trying to consolidate some links I’m finding useful for trend analysis, where tech could be headed, as well as future learnings. This format is my feeble attempt at organizing 🙂 More Code, Less Typing Visual Studio https://channel9.msdn.com/Shows/Visual-Studio-Toolbox/More-Code-Less-Typing if it ain’t Core you should code with it no more https://www.theregister.co.uk/2019/06/10/core_wcf_wf/ Pimp my PowerApp https://www.theregister.co.uk/2019/06/11/microsoft_adds_ai_builder_to_power_bi_tools/ The Future of Web Animation The CSS Mindset https://mxb.dev/blog/the-css-mindset/ The Documentation Compendium https://github.com/kylelobo/The-Documentation-Compendium Advertisements Share this: Twitter Facebook Like this: Like Loading...
  70. Adam Argyle
    mild mannered sane advice 👍
  71. Richnou
  72. Créer Un Site Pro
    L'état d'esprit qu'il faut pour faire du #CSS ! mxb.dev/blog/the-css-m…
  73. Clever Cloud
    [news] 🗞 The CSS Mindset mxb.dev/blog/the-css-m… (blog) #CSS
  74. Paviel Łaŭcevič
    There are so simple things described in this article, which are ignored by a huge amount of developers. Try to understand this and you'll love #CSS! 👍 mxb.dev/blog/the-css-m…
  75. Erik Zettersten
    The CSS Mindset | Max Böck - Frontend Web Developer mxb.dev/blog/the-css-m…
  76. Ash
    The CSS Mindset. “It’s better to be explicit.” “In most cases, it’s better to define a rule for the intent, rather than hard-code the computed solution to it.” Much more wisdom within! mxb.dev/blog/the-css-m…

Featured Blog

Heydon is a designer and accessibility consultant based in the UK. He wrote 'Inclusive Design', edits for Smashing Magazine and is an excellent speaker on all things a11y.

Read More