Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Created April 20, 2020 17:21
Show Gist options
  • Save tomhodgins/4119930db493c2c3c0920bfbfed4223f to your computer and use it in GitHub Desktop.
Save tomhodgins/4119930db493c2c3c0920bfbfed4223f to your computer and use it in GitHub Desktop.

CSS explained for programmers:

  • CSS is a stylesheet language, it's built around rules which contain 'declarations' of properties
selector {
  property: value;
}
  • There are also conditional rules that contain other rules (like @media and @supports and more)

  • Some rules can also be a single line like @import 'url';

  • The main goal is to apply style properties to nodes in a tree structure (DOM, the parsed HTML, XML, SVG, or MathML document in the browswer)

  • You can apply these properties individually to each node in the tree yourself (inline styles with style="") but that's not very high level or declarative, and a cumbersome job to actually get done…

  • so the way CSS helps you is it lets you store grouping of properties and values you want to apply and allows you to write 'selectors' that match 0-∞ tags in the document.

  • If you like functional programming, you can think of CSS selectors lists as a DSL for filtering lists of DOM nodes with extra goodies like logic (:not()) or also sometimes use descriptions of relationships between nodes as a way to target them

  • Now that you have potentially many rules applying many properties to many nodes in a DOM tree, if the same style property is declared more than once, how do you resolve which one it should be? A naive implementation might just say last-set-value always wins, but in CSS things like the origin of the stylesheet, the order of the rules, and the 'specificity' (kind of like complexity) of the selector used to target the elements in the various rules that contain the properties as part of how it resolves which property value should 'win'

  • To save you from having to declare every value for every element, there's also a concept of 'inheritance', and some properties inherit and some dont. You can look that up on a per-property basis. (Also some things are 'animatable' and some aren't)

  • Lastly, browsers provide a basic CSS stylesheet for the elements in HTML so they're not 100% unstyled, so as you're writing CSS keep in mind it's not truly a blank slate you're building on top of, but some sensible and basic defaults

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment