
Things I wish I’d known about CSS - harshamv22
https://cssfordesigners.com/articles/things-i-wish-id-known-about-css
======
k__
It always helped me to do an absolute basic concepts course on a new
technology I learn.

Like, sure I can play around in Photoshop or Eclipse or CSS or JavaScript and
find most things.

But a good 101 course is worth so much saved time.

Most of the stuff in that article was mentioned in a CSS box model course I
did 10 years ago.

People were always baffled how I learned all this. Well, I read the docs!

They always assume every one learned like them, by trying stuff out all of the
time, until they got something working. Then they iterate from project to
project, until they sorted out the bad ideas and kept the good ones. With that
approach, learning CSS would probably have taken me 10 times as long.

Sure this doesn't teach you everything or makes you a pro in a week, but I
always have the feeling people just cobble around for too long and should
instead take at least a few days for a more structured learning approach.

What I didn't learn about CSS in a basic course and what cost me multiple
weeks to fix, was `pointer-events: none`. Keep this in mind when your clicks
stop working after you pulled some new CSS ;)

~~~
theelous3
Cobbler here, currently cobbling a frontend (am a backend dev by trade).

The issue for me is the format these courses and resources take. CSS is the
most jam packed with non-intuitive technology I've met. How many dozens of
pages or segments of video would I have to go through in a course to learn
what the author in OP summarised in two or three sentences? Any time I've
considered the structured approach for something like CSS, the material drones
on and on with technically correct explanations and example code, but somehow
against the odds, almost nothing of substance.

Worse yet are the top google result reference resources. Look no further than
the top result for "css grid" if you're in the mood to claw your brain from
its stem, and flush it down the toilet.

Link: [https://css-tricks.com/snippets/css/complete-guide-grid/](https://css-
tricks.com/snippets/css/complete-guide-grid/)

Behold, 8 zillion words and symbols across 7 trillion seemingly randomly
organised boxes full of both all of the information, and simultaneously none
of the information, about css grids.

Which brings me to where I am now, cobbling. It's more effective for me to
cobble, than to spend an entire day figuring out css grids "the right way". If
the going gets tough I'll just use some grid tool, or look up some sandbox
examples, and be on my way.

If there was more material like the OP, and someone organised it well, well,
I'd actually get around to learning it rather than cobbling. It's the best bit
of writing I've ever seen on CSS. This is shocking. Not that there is anything
wrong with the writing, but it's very, very simple. What on earth have all of
the other CSS wizards with basic writing skills been doing? Confusing the
issue, that's what.

Which leads me to a sort of meta frustration with learning CSS. I know it's
not hard, I know that if someone just wrote about it even half decently it
would take only a moment to digest each concept, but watching learner-
disconnected authors create resources I can tell have lost sight of what it's
like to learn, turns me off.

~~~
mslm
I had the same perspective on these frontend technologies as a backend/ops
guy, and it all finally clicked when it came to me that I just couldn't find a
justification for why CSS was the way it was.

This was solved trivially by just reading the history of CSS. It was shocking
to finally have made clear all of the quirks and weird aspects of CSS that
always made it difficult for me to connect the dots and feel myself lost in a
messy tangled up language.

By far the best source I went through was found here:
[https://news.ycombinator.com/item?id=22215931](https://news.ycombinator.com/item?id=22215931)
\- it's a long read, but extremely enlightening!

[https://www.w3.org/Style/CSS20/history.html](https://www.w3.org/Style/CSS20/history.html)
was also useful.

~~~
_jal
This is a great comment. I expect it only applies to some folks depending on
how they learn, but it resonates a lot with me.

I find it very difficult to learn the whats and hows of a new thing without
the whys. I tend to construct mental frameworks of things, revising the
inaccurate bits as I go, until theory starts meeting practice. (I always did
poorly with math "teachers" whose method was, "doesn't matter, just do it."
But it did take a while to realize that they were failing, not me.)

So when I encounter complicated, new things with a history, I usually try to
start with at least a bit of the history.

------
cookiengineer
Meanwhile, this is, oh so damn outdated. (I'm not kidding)

Most people don't know that the flow model totally changed meanwhile, and
something like "display: inline-block" actually means "display: inline flow-
root", everything that came after flexbox kind of had an influence to the
meanwhile borderline insane display model as a result.

Everything related to inset, margin and padding has gotten an overhaul that is
ready for ltr and rtl content where they switch x/y flow based on "direction:
ltr (or) rtl" whereas e.g. "margin-inline" and "margin-block" are the newer
properties for the updated margin.

A lot of stuff has changed for the better, too.

CSS transforms are now specified in a cleaner way, with a predictable way to
render them (e.g. translate rotate will not be different than rotate
translate). So all CSS transforms have gotten their own properties like
"rotate: 90deg" or "scale: 1.23".

I learned a lot when I read through the actual CSS specifications, because I
am implementing my own parser (for my Browser [1] project).

Also, did you know that @media, @supports and @viewport queries can be nested
in any order? The media queries 4 [2] spec is kind of insane from an
implementor's view.

[1]
[https://github.com/cookiengineer/stealth](https://github.com/cookiengineer/stealth)
and
[https://github.com/cookiengineer/stealth/blob/X0/FEATURES.md](https://github.com/cookiengineer/stealth/blob/X0/FEATURES.md)

[2]
[https://www.w3.org/TR/mediaqueries-4/](https://www.w3.org/TR/mediaqueries-4/)

~~~
andrewmcwatters
I'm a layout implementor for Planimeter's Grid Engine. Implementing a naive
subset of the algorithm for calculating the box sizes in the visual formatting
model and calculating layout for normal flow, relative positioning, and
absolute positioning is far easier to implement than flexbox.[1] There's
nothing insane about this. And you'll learn even more when trying to draw to
the screen.

Normal flow also doesn't require multiple passes, whereas flexbox does.[2]
Even Yoga doesn't implement a conforming model.[3] I'd even speculate that
flexbox performs slower than the standard visual formatting model just because
of the differences in the algorithm.

Transform order absolutely matters. Any attempts to coerce order into a
standardized sequence means developers have to account for this
information.[4]

[1]: [https://github.com/Planimeter/grid-
sdk/blob/master/engine/cl...](https://github.com/Planimeter/grid-
sdk/blob/master/engine/client/gui/box/init.lua#L158) [2]:
[https://www.w3.org/TR/css-flexbox-1/#resolve-flexible-
length...](https://www.w3.org/TR/css-flexbox-1/#resolve-flexible-lengths) [3]:
[https://github.com/facebook/yoga/blob/master/yoga/Yoga.cpp#L...](https://github.com/facebook/yoga/blob/master/yoga/Yoga.cpp#L2382)
[4]: [https://docs.microsoft.com/en-
us/dotnet/framework/winforms/a...](https://docs.microsoft.com/en-
us/dotnet/framework/winforms/advanced/why-transformation-order-is-significant)

~~~
irrational
What are your thoughts on CSS Grid? Does it require multiple passes?

~~~
c-smile
If the question is about layout computation then CSS Grid layout (and ideally
<table> layout) is a typical LP task [1].

And there are known way of solving these things, e.g. simplex methods or
Cassowary constraint solver (CCS)[2] will work.

In fact flexbox layout is a particular case of LP task and also can be solved
by CCS efficiently.

[1]
[https://en.wikipedia.org/wiki/Linear_programming](https://en.wikipedia.org/wiki/Linear_programming)
[2]
[https://en.wikipedia.org/wiki/Cassowary_(software)](https://en.wikipedia.org/wiki/Cassowary_\(software\))

------
techbubble
This was a great article and I learned a few new tricks.

I learned CSS over the years by gradually solving problems I encountered
building apps. Compare this to people learning CSS now as evidenced by the
#100DaysOfCode tag on Twitter. The learning technique is comprised primarily
of using gradient-heavy, absolutely positioned HTML elements to create a
photo-realistic, 3D rendering of objects.

The results are pretty amazing, but I have my doubts about whether these
skills are easily translatable for building an interactive, responsive UI.
Some examples:

[https://twitter.com/bauervadim/status/1282264611912327169](https://twitter.com/bauervadim/status/1282264611912327169)

[https://twitter.com/mercyoncode/status/1282449080132804609](https://twitter.com/mercyoncode/status/1282449080132804609)

[https://twitter.com/ellie_html/status/1276177277315932161](https://twitter.com/ellie_html/status/1276177277315932161)

[https://twitter.com/thecoffeejesus/status/128204582508278169...](https://twitter.com/thecoffeejesus/status/1282045825082781696)

[https://twitter.com/alyd789/status/1271200537988431873](https://twitter.com/alyd789/status/1271200537988431873)

~~~
umaar
I learnt CSS in a similar way. I'd take Photoshop designs and try to recreate
them in vanilla HTML + CSS:

[https://jsfiddle.net/umaar/YNA5V/](https://jsfiddle.net/umaar/YNA5V/)

[https://jsfiddle.net/umaar/fu4TT/](https://jsfiddle.net/umaar/fu4TT/)

I'd even make 3d graphics of things like the HTML5 logo:
[https://i.imgur.com/kuEYpSV.png](https://i.imgur.com/kuEYpSV.png)

I posted this all to a community called "Forrst" (think of it like twitter,
but curated for developers and designers).

I spent time giving feedback on other peoples work, I tried to ask insightful
questions
[https://twitter.com/umaar/status/823915022917271552](https://twitter.com/umaar/status/823915022917271552)
to have an open discussion, I spent hours replying to comments every few days.

Then one day, Forrst got acquired by Zurb [https://zurb.com/blog/zurb-
acquires-forrst](https://zurb.com/blog/zurb-acquires-forrst) and later on it
got shut down, and with that, I lost access to huge amounts of my work which I
hadn't stored anywhere else (some stuff has been archived online, but not
everything).

When it comes to web development tips, I now self-host on my own website and
it's a really good feeling knowing that it'll be preserved:
[https://umaar.com/dev-tips/](https://umaar.com/dev-tips/)

~~~
techbubble
I like what you have done with the site — very simple and easy to check out
the tips. I subscribed.

~~~
umaar
Hey thanks for that appreciate it. Yes not spending time on fancy
things/random enhancements let's me actually focus on creating new content.

------
c-smile
I believe that focal point of CSS understanding is that horrible _display_
property. People just need to get that one as other stuff is relatively
trivial.

display:xxx on some elements defines three things ( sorry, that is terrible
architectural mistake authors of CSS have made initially )

1\. display defines "sibling requirement" how that element wants to be
replaced among its neighbors. `div {display:inline-box}` tells container to
treat that div a single glyph placed inline among other glyphs.

2\. In some cases it also defines "layout manager" of element's content. E.g.
display:table and display:inline-table tells the renderer that content shall
be treated as table having tbody , rows, cells, etc. Same thing for
display:flexbox, grid, etc.

3\. In some cases it defines other things like display:none; display:list-
item; Note: there is still no display:inline-list-item ...

Ideally we should have these instead:

1\. display: inline | block; - and just these two.

2\. flow: auto | text | table | vertical | horizontal | grid...; - defines
layout manager of element's content.

3\. visibility: visible | hidden | _none_ ; - Note: visibility:none instead of
display: none;

~~~
runarberg
Don’t forget `display: contents` in which the element is instructed not to
generate a box at all (neither inline nor block; I guess like `display: none`
without hiding the content).

But I think the spec maintainers are aware of this and CSS Display Module 3[1]
allows multi-keywords so you can do stuff like:

    
    
        display: block grid;
    

or:

    
    
        display: run-in ruby;
    

or even:

    
    
        display: inline flow-root list-item;
    

1: [https://drafts.csswg.org/css-display/#the-display-
properties](https://drafts.csswg.org/css-display/#the-display-properties)

~~~
c-smile
That is not a fix - just a cosmetic change that does not solve anything.

display/flow MUST BE [1] different properties as they define orthogonal
concepts.

We should be able to define them separately.

    
    
       main { display: block;  flow:grid; }
    
       @media handheld and (width < 100mm) {
         main { flow:vertical; }
       }
    

Yet _none_ from _display_ shall go to visibility:none (as in my Sciter [2]).

I've seen too many times errors like this:

    
    
       main table { display:none; } 
       main.full table { display:block; } 
    

Which is obviously wrong, <table> element should have display:table or
display:inline-table;

[1] [https://tools.ietf.org/html/rfc2119](https://tools.ietf.org/html/rfc2119)
[2] [https://sciter.com](https://sciter.com)

------
hellofunk
Yikes. I've been earning 6 figures as of about two years ago doing mostly HTML
and CSS UI design for a bank. And I still did not know about many of these! I
guess they are things I wish _I 'd_ known about CSS! Better late than never I
guess.

~~~
ChrisRR
Six figures? In the US?

Sometimes I wonder why companies even pay developers so much in the US. I'm a
specialised medical embedded software developer in the UK and I'm not even
halfway to six figures, and will likely never hit it.

It astounds me that companies don't hire twice as many non-US developers for
the same price and get more work for their money. Note, I'm not talking about
outsourcing to the absolute cheapest bottom of the barrel developers who cost
1/20 of the price and the quality reflects the price. Just equally skilled
developers in non-US countries.

~~~
speedgoose
The US salaries in IT are huge, but you need to take into account that they
have to pay a lot to have a quality of life comparable to what a minimum wage
worker is getting in west Europe.

If you have a few kids, I would bet you are not that bad in UK with one fewer
digit.

~~~
rusticpenn
Yes, This is the main difference. In Germany the education is free and medical
insurance not something to worry about ( I have no idea about what
deductables, deletables etc mean). This is where the difference lies.

~~~
wirespot
As simple rule of thumb an employer in the EU has to pay roughly double the
net salary amount, so on top of the salary pocketed by the employee yet
another similar amount goes to taxes. The education/insurance aren't "free",
they're just managed better and give more direct benefits to the taxpayer.

~~~
rusticpenn
It depends. When I was a student, I did not have to spend a penny on medical
biils, my wife got paid by the government for some courses (+ cost of rent
etc) that would have costed us around 20K € at that time. Now that we are
earning enough, I have no problem in paying back, so that others who need it
will be also be able to achieve their dreams.

------
leephillips
I don’t thnk the author’s recommendation to include

    
    
         img {
            display: block;
         }
    

in your reset is generally a good idea. It will break some common uses of
images, for example to hold bits of math inline with the text when you are not
using mathjax. If you want a displayed image, you should wrap it in a <figure>
tag, which will give you a block element.

~~~
chrismorgan
If you wrap an image in a figure, but leave the image still inline, you’ll
probably get a few pixels of extra space at the bottom of the image due to
line-height and vertical-align. People find that _really_ confusing. With how
most people use images, I agree that `img { display: block; }` is what you
want >99% of the time, and would rather people reverse it for the rare
occasion when they want something else. (BTW, doesn’t MathJax emit SVG? _Viz._
, not <img> anyway.)

~~~
leephillips
I’m confused by your reply. Did your eye skip over the word “not” in my
comment?

~~~
chrismorgan
Sorry, you are correct. Drop the final parenthetical, then, but I stand by the
rest.

~~~
leephillips
Yes, your other point was something I hadn’t thought about. I guess his advice
would be good for some people, but I’m not sure about the 99%. It’s not
uncommon to use small images as text-like elements, and when you do that, if
you have this reset, you will need to explicitly make them inline. Not a huge
deal, but people tend to copy and paste their own CSS libraries between
projects, and redefining basic default semantics of elements may create
confusion and extra work down the line when things don’t behave the way that
any documentation you may consult assumes.

~~~
chrismorgan
I’m going to stick with the >99% figure. I think it _is_ uncommon, rare even.
Other than chat systems with custom emoji rendered as an img, I honestly can’t
think when I last saw a site with inline <img> tags. (I’d _guess_ it to be
within the last month, maybe even the last week, but it wouldn’t surprise me
if it wasn’t.) Twenty years ago, sure, but they’ve gone out of fashion
stylistically as well as technically. Technically, I suspect background-image
and icon fonts are both used more commonly for small iconography.

~~~
leephillips
It depends on what kind of sites you tend to visit, I guess. I see this
several times per day. But I often visit pages with math on them. Before
mathjax became standard, inline images was the only way to do it. And visit
any Wikipedia page with math: they use mathML and have fallbacks, but the end
result is, you are looking at inline images. Also, I often see such things as
sparklines and similar things, also inline images. The >99% may be true of
what you consume, but without data I am skeptical about the numbers.

Also, some people use CMSs that substitute inline images for missing Unicode
glyphs, and other things. If it’s done well, you may not even notice. You
don’t know if the correct figure is 99% unless you have examined the source of
a sample of sites.

------
paozac
Useful article. Getting started with CSS must be harder these days than it was
15-20 years ago. Not only for mobile-friendliness, but also because of the
coexistence of flexbox/grid/traditional layouts. I'm wondering if the standard
will ever been simplified, instead of being added more and more features.

~~~
_the_inflator
CSS and HTML are constantly evolving, and so its demands. However for me CSS
is way more straight-forward than in the 90th and 00th.

The standards addressed a lot of the pains and struggles we had with
floats/clearfix etc. This was challenging but nothing im comparison to
supporting IE 6-9, FF, Safari, Opra etc. at the time. Also hacking in
JavaScript added to the complexity.

Nowadays I can do with 10 lines of grid and flex what great CSS frameworks
like Bootstrap abstracted away behind 1000th of lines of code.

Also testing is way easier, since browser vendors follow standards and there
is chromium everywhere.

Earlier we did a lot of div soup, I remember fondly CSS zen garden as well as
OneDiv.

Awesome times to be a web dev, you work on products (PWAs!) not on browser
hacks.

My 2 cents.

~~~
techbubble
"div soup" – I like that.

The present-day CSS frameworks use "class soup."

For example, tailwind (which I like):

    
    
      <button class="bg-teal-500 hover:bg-teal-600 focus:outline-none focus:shadow-outline">

~~~
runarberg
This sort of class soup brakes the principal of DRY. Much better to use CSS to
style.

    
    
        button {
          --background: teal;
          --focus-ring:
            2px 2px 5px skyblue,
            -2px -2px 5px skyblue;
    
          background: var(--background);
          box-shadow: none;
        }
    
        button:hover {
          --background: wheat;
        }
    
        button:focus-visible,
        button:focus:not(:focus-visible) {
          outline: none;
        }
    
        button:focus-visible {
          box-shadow: var(--focus-ring);
        }
    

Now you will never forget to add that `hover:bg-teal-600` class to your
buttons.

------
wruza
Guys we need to talk. Are you capsbold serious? These are things that you
learn in a first week of doing web development tutorials. I read this thread
and it makes me think that I'm delusional because of a heat wave. Margins
collapse? :focus exists? Me not getting a joke? I don't understand.

~~~
nanna
I think you may be underestimating the fact that many people have been writing
CSS for well over a decade now, and that it has evolved considerably since
they first read a web development tutorial. If you've not been paying close
attention (or not been able to), there are many things that will have passed
you by.

It's a blessing to learn css fresh today, in as much as it's a curse to still
have practices from ten years ago still lodged in your memory.

~~~
Izkata
> and that it has evolved considerably

GP is pointing out the parts that haven't changed at all, and are old (over
two decades), simple, and common enough to be considered basic knowledge. I
had the same reaction to those and one or two others.

Now if this was someone relatively new to CSS I'd understand, but the opening
paragraph establishes how long this person was around. Padding-vs-margin in
particular was necessary knowledge to do good layouts back in those earlier
days (less so now only due to flex and grid, which aren't on here).

~~~
nanna
> GP is pointing out the parts that haven't changed at all

Doesn't read that way to me:

> These are things that you learn in a first week of doing web development
> tutorials.

Sure, padding vs margin isn't exactly new, however `display: inline-block`,
::before and ::after, rem, ch, and :nth-child() certainly weren't in the old
html4/xhtml and css2 guidebook that got me into web development!

~~~
nanna
To add, I think another post by the same poster on this HN post proves the
point that they're not dismissing individual parts, but rather disputing (or
sorry but trolling) the article as a whole:

> I think (hope, really) that gp is just one heavy "/s". The knowledge
> presented in the article is so basic that it is hard to believe that a
> person who does html for two years and six figures doesn't know these. As
> for the article, I fail to see any reason for it to exist beyond cheap media
> presence. Or maybe I should start a blog, because I'm not even halfway too.

~~~
wruza
I was disputing the article in a comment that you quoted, and this thread's
other comments in ggggp, if it may help with the investigation.

------
c-smile
There are couple of things that author still don't get.

display:inline means that element does not establish a box. Such element is
rather a collection of individual content boxes (e.g. glyphs). These boxes can
be placed on different lines (text wrapping) and so on. As no element box as
no margins and paddings applied to such elements.

img element (and input and other replaced(^) elements for that matter) is not
a display:inline but rather display:inline-block. Even you will define them as
display:inline they will be treated as display:inline-block and so e.g.
margins will apply to them.

(^) representation of replaced elements (img,input,textarea,iframe,etc.) is
outside the scope of CSS - they are always treated as solid boxes.

------
jitendrac
That is really useful.

I have been writing small html front-ends since 2008-09. HTML5,CSS3 made many
things easier like gradients, Round borders, and many things that now
developer do takes as granted. I clearly remember, how boring and frustrating
it was to slice borders and corners from photoshop psd.

CSS3 and HTML5 made many good changes, but new css feature like grid, Flex-box
all are still confusing. I have to look at the references every time I start
new frontend work.

~~~
dgb23
Have you ever taken some deliberate time to really „play“ with those?

My recommendation: take a calculator or spreadsheet and start with some simple
cases and build up your knowledge in a exploratory manner. A few hours, a
session for each feature (flex, grid).

Its not only fun but also really helpful!

~~~
mellow2020
> Have you ever taken some deliberate time to really „play“ with those?

I know just the thing!

[https://flexboxfroggy.com/](https://flexboxfroggy.com/)

[https://codepip.com/games/grid-garden/](https://codepip.com/games/grid-
garden/)

~~~
jitendrac
Thanks, froggy was on front page of HN so I knew it for sure, grid garden is
new one for me.

------
andi999
Anybody knows a good book on CSS for ppl with a solid programming background?
Every couple of years I try something and fail. Somehow the tutorial rave
about the cascading on and on, and when it comes how to strategically design a
good SAP working on different devices the stuff gets mute quickly.

~~~
noir_lord
Not a book but [https://developer.mozilla.org/en-
US/docs/Web/CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) is my go-to
for all things CSS, I love mdn it's a fabulous resource.

Also zeal (dash on Mac which is paid or you can build zeal yourself like I
did) has docsets for CSS which are good.

~~~
dwd
[https://caniuse.com/](https://caniuse.com/) is also invaluable to check
whether the cool CSS feature is actually supported. it's very much today's
quirksmode.com.

Once upon a time I would have recommended Eric Meyer's CSS Definitive Guide
without hesitation (I think I still have my 1st Edition copy) and it looks
like he's re-released with updates for flexboxes and grids.

------
gorgoiler
It feels like HTML and CSS could be useful for print layout, but I’ve rarely
seen a high quality PDF renderer.

I know Atom’s markdown preview uses headless chrome under the hood. These are
hugely heavyweight tools but the output is very high quality.

Are there any other recommended tools for going an HTML route, for
typesetting? I’d much rather design pages that way than use InDesign, PDF
scripting, or TeX.

~~~
mkayokay
I have been using Python with Jinja2 templates and Weasyprint[1] for PDF
creation for a side project of mine. The libary does have its css limitations
but the PDFs it produces look good enough for me.

[1] [https://weasyprint.org/](https://weasyprint.org/)

~~~
elondaits
Yes, I was going to recommend WeasyPrint as well.

------
continuational
> Using pixels (px) is tempting because they’re simple to understand: declare
> font-size: 24px and the text will be 24px. But that won’t provide a great
> user experience, particularly for users who resize content at the browser
> level or zoom into content.

Pixels (px) in CSS are relative as well, and scale with zoom. What is the
benefit of em/rem?

~~~
chmod775
>What is the benefit of em/rem?

They (em*) scale with the element's font size, and if you set an elements
font-size itself in em, that will be relative to the parent element's font
size.

For example:

    
    
        body { font-size: 18px }
        .something { border: 0.1em solid black; }
        .something > .inner { font-size: 1.5em }
    

If you change the font-size on body, everything on that page will re-scale
seamlessly. This is most useful for things like buttons/icons that are
supposed to flow properly with text. So now even if you use them once in big
text, and once in a small footnote, they'll still fit perfectly within the
line.

The biggest limitation to this approach is that you can easily end up with
computed values that are weird fractions of pixels, so you have to be a bit
smart and pick an easily divisible number for your base font-size if you're
aiming for something pixel-perfect.

~~~
onion2k
The challenge with em units is that if you modify a parent element's size it
changes the children as well. In your example, if you put 'font-size: 2.0em'
on the .something class then the .inner would end up changing to 3.0em. That's
rarely what you actually want to happen (especially in a web app). If you just
want to control the overall font scaling of everything on the page using rem
is preferable, because then they'd ignore the parent and scale based on the
root element size.

~~~
bbx
The key is to use rem for font-size and em or unitless for all other
properties: padding, border-width, margin, line-height. That way the size of
the element is independent of the context.

------
chrisweekly
If you're looking for world-class CSS knowledge, start with [https://every-
layout.dev;](https://every-layout.dev;) if you build UI for a living and
haven't encountered axiomatic css and layout primitives, they're likely to
change your world.

~~~
randompwd
To save clicks, it's $100, just covers page layouts.

~~~
chrisweekly
That's a radically misleading comment. It covers much more than layout, and
the free content on the site is incredibly helpful and compelling. The full
version more than justifies its price. And they offer it for free to students
or anyone else for whom the cost is a problem (relying on the honor system).

It's far and away the best resource on CSS I've encountered in my 22-year
career working with web technology for a living.

No affiliation, just a grateful patron.

~~~
randompwd
not that the free thing is relevant but from [https://every-
layout.dev/blog/you-pay/](https://every-layout.dev/blog/you-pay/) "The honour
system is now closed"

> That's a radically misleading comment. It covers much more than layout

Given the site and all 3rd party reviews just mention layout, how is it
misleading? Cant find TOC anywhere?

Also, found working discount code 'BRANDEMIC' for 60% off in my travels should
any1 bite the bullet.

prev hn sub/182 comments:
[https://news.ycombinator.com/item?id=20196061](https://news.ycombinator.com/item?id=20196061)

~~~
chrisweekly
Ok,I missed that the honor system closed recently - but they continue to give
it away freely to students or those facing hardship, on request.

The focus of course is on layout (by far the hardest part of CSS to get
right), but it's in the context of building up your entire UI from robust,
composable, accessible, standards-compliant, profoundly well-engineered
primitives, based on first principles -- which principles are clearly
articulated and demonstrated in the site.

It also covers typography (IMO by far the best explanation I've encountered of
_why_ to use a typographic scale as the foundation of your design system), as
well as touching on things like web components, shadowDOM, custom properties..
. and providing a deeply-expert perspective on the relative merits of utility
classes (a la Tailwind et al), among other approaches.

I've been working in web-related roles for a living for over 20 years and have
never once encountered a CSS-related resource that was this compelling and
useful.

"Can't find TOC"? Um, it's in the site's primary navigation, in the left
column. Literally impossible to miss.

I paid the full $100 and was glad to do so. The authors aren't popular
(they've clashed on twitter with some big-name FE people like MDalgleish) but
their ideas and body of work are unparalleled, and that's what I support.

If I were more selfish I might try to keep my newfound FE superpowers
[axiomatic css and composable layout primitives are transformational] a
secret, but I find myself wanting to spread the word and support
[https://every-layout.dev](https://every-layout.dev) every chance I get.

------
yakshaving_jgt
Cached URL since the server is apparently over capacity:
[https://webcache.googleusercontent.com/search?q=cache:jcSTVF...](https://webcache.googleusercontent.com/search?q=cache:jcSTVFGdcZAJ:https://cssfordesigners.com/articles/things-
i-wish-id-known-about-css+&cd=1&hl=en&ct=clnk&gl=ua)

~~~
rapnie
Now on [http://archive.is/AiECQ](http://archive.is/AiECQ)

------
jraph
An element that has:

    
    
        display: inline-block
    

is inline outside, block inside.

That is, the element is inline for the containing block, but its children feel
like they are in a block.

An inline-block element can be vertically aligned with respect to the
baseline: it acts a bit like a character in a paragraph. That's why you can
vertically center things using vertical-align:center on an inline-block
element.

At least, this is my intuition of inline-block, this comment is far from being
normative.

~~~
runarberg
To be even more pedantic: It is inline outside and _flow-root_ inside. From
MDN:

> The element generates a block element box that establishes a new block
> formatting context, defining where the formatting root lies.

[https://developer.mozilla.org/en-US/docs/Web/CSS/display-
ins...](https://developer.mozilla.org/en-US/docs/Web/CSS/display-inside)

~~~
jraph
Ah but then it does not work as a mnemonic anymore!

I'm kidding. Thanks, TIL I learned that with now have display-inside and
display-outside (and flow[-root]). This makes perfect sense. Finally, even,
I'd say. Having a property that defines both the behaviors of an element
outside and inside without being able to define these behaviors separately was
both strange and limiting. I'm happy I even used the terms that have been
chosen to speak about these notions in CSS by chance.

How do you track all these useful additions to CSS conveniently though? I
can't rely on random comments on HN to learn about them by chance (no offense
intended to your valuable comment btw, being random is perfectly fine). I also
can't possibly systematically learn about each and every addition neither. Are
there resources addressing this?

~~~
runarberg
I recommend taking the State of CSS[1] survey, it is a nice way of keeping up
with the latest features. Other then that I use PostCSS with the postcss-
preset-env[2] plugin. There you can enable various future features of the
language and have it compile down to a more supported version. If your
_really_ want to dive into the future of CSS you can read the issue board for
the CSSWG[3] (beware, it can suck hours out of your days). Smashing
Magazine[4] and A List Apart[5] also sometimes have articles about a new(ish)
or upcoming features.

But the CSS community could _really_ benefit from the spec maintainers having
more active bloggers among them (e.g. like Rachel Andrew[6]) and provide a
regular update of the language like 2ality does for JavaScript[7].

1: [https://stateofcss.com/](https://stateofcss.com/)

2: [https://preset-env.cssdb.org/](https://preset-env.cssdb.org/)

3: [https://github.com/w3c/csswg-drafts](https://github.com/w3c/csswg-drafts)

4: [https://www.smashingmagazine.com/](https://www.smashingmagazine.com/)

5: [https://alistapart.com/](https://alistapart.com/)

6: [https://rachelandrew.co.uk/](https://rachelandrew.co.uk/)

7:
[https://2ality.com/2019/12/ecmascript-2020.html](https://2ality.com/2019/12/ecmascript-2020.html)

~~~
jraph
Thank you very much :-)

------
ChrisMarshallNY
That’s useful.

Some time ago, I wrote up a series about CSS. It’s still quite relevant (but
CSS has come quite a ways, since then).

The thing I’ve found that is often misunderstood, is specificity. It’s a
fairly non-trivial concept:
[https://littlegreenviper.com/miscellany/stylist/introduction...](https://littlegreenviper.com/miscellany/stylist/introduction-
to-specificity/)

------
dzink
20 years ago knowing CSS’s inheritance and tree traversal structure was
critical to finish sites that worked flawlessly across all browsers. There was
a lot of beauty in it, so much so that borrowed some ideas from CSS models for
the architecture of the custom template system behind the CMS that powered CNN
and a number of other large media sites with many sub-properties.

------
aliswe
A little secret opinion of mine is that I think the global usage of rem
instead of px is a fad. The only real argument I've heard is that the mobile
devices have their own definition of it, and will thus optimize in their own
way, but then again I see that benefit as being nearly non-existant and
definitely not demonstrated.

~~~
rob74
It's a fad nowadays, but if you remember the bad old days when the "zoom"
function in browsers was useless on most pages, that was because the browsers
did it "by the book": they only zoomed elements with relative sizes, px units
were always pixels. Then browser makers just gave up and reimplemented the
zoom function to work with "broken" pages too (I think Chrome did it first and
the rest followed suit). Of course the advent of Hi-DPI screens probably also
played a part...

------
acqq
Apart from the course promoted (which sounds really good!), does anybody know
a really good book that already presents this kind of material about CSS use
in a similar "logical" way and is not being written the style "margin defines
the margin" (how insightful)?

I'm also searching for the material that is specifically oriented on:

\- depending on the features existing in all browsers since the last 3-4
years, also mentioning how to make the features "usable" with the older vendor
prefixes, but not depending on the JavaScript "fixes" for older browsers, and
then showing the examples with minimal number of lines.

\- demonstrating all the functionality that can be achieved with CSS only, no
JavaScript

\- addressing the real-life problems encountered during the design of the
modern looking pages, and the goal to use all the power of the commonly
available CSS features.

------
swyx
for people who want to go deeper on stuff like the box model and specificity
and selectors, i highly highly recommend Una Kravets and Adam Argyle's The CSS
podcast [https://pod.link/thecsspodcast](https://pod.link/thecsspodcast) \-
they are the two CSS devrels from google and they really break it down in
depth while explaining things in an accessible way. no vested relationship,
just a fan.

------
xanathar
Ends up to a page saying "The page you requested does not exist".

...which kinda reflects "things I wish about CSS", so 10/10.

~~~
zero_iq
Page doesn't render correctly for me in Firefox/MacOS, so I had a similar
thought... there's probably a couple of things he should add to his list! :D

~~~
Wowfunhappy
Same here (and same browser/OS), it seems like some font is missing?

------
superasn
This is content marketing done right. I really don't mind that this article is
there to promote the book when it actually offers some value to the reader (I
actually learned a new thing, nth-child and nth-of-type)

------
geewee
This is actually really nice. I've worked with CSS for a long while with the
"Stackoverflow it until it works" philosophy, so some of these things (e.g.
margin collapses) I had no idea about.

------
Phillips126
Good stuff here, I certainly learned a few new tricks.

I've been doing web development since around 2005 and to me, CSS and HTML has
become far easier to use (although that could also be from experience). I took
a web development course in college and found it interesting, later joining a
small marketing company as an intern. My internship was unique, the company
would travel to local businesses and sell them on advertising. They'd record a
small ~2 minute commercial showcasing their business and then I'd build an
application that compiled all of this data into a "local tourism" application.
The real kicker - we didn't host the content, we burned it onto CDs and
distributed the discs (think AOL). The company didn't profit well, but it was
small and able to survive on what income it did make. I'm actually surprised
to see it still around today - however, it seems they've moved on to actual
hosted web development and graphic design work now. During this time we mostly
used a combination of Tables and Photoshop "slices" to do layout (yuck!).

Today I use CSS/HTML/JavaScript daily building internal applications (and a
few external). There is certainly more things to worry about such as building
applications that are responsive now that mobile devices are so prevalent,
however my arsenal has improved dramatically over the years with the addition
of Flex and Grid (and many others). I actually enjoy the challenge of creating
something beautiful and functional.

------
amanzi
This is great! I've been hacking away at CSS for years and learned heaps from
this. Also, reminded me to look up the differences between `rem` and `em`,
which I've been meaning to do for ages!

[https://j.eremy.net/confused-about-rem-and-em/](https://j.eremy.net/confused-
about-rem-and-em/)

------
maweki
I think a better understanding between inline and block is, that inline-
elements do not generate a block. The idea of a block breaks down for inline
elements, especially when they go over multiple lines. It's not just a
horizontal expansion.

So understand what creating a block means. Inline-elements don't.

~~~
swyx
how does this help explain inline-block? your explanation must accommodate the
holes.

~~~
aflag
In his explanation inline-blocks do generate a block. It's just a block that
doesn't fill the entire horizontal space, but expands with the inner element.

------
pansa2
> _If your CSS reset doesn’t include this already, I’d suggest adding the
> following rule: ..._

If I'm trying to build a site design from scratch (rather than using Bootstrap
or similar), is a CSS Reset a good place to start? Is there one in particular
that's recommended?

~~~
themodelplumber
It can be a very helpful start, but I'd review to make sure you're learning
from it as well, rather than building onto something that could set you up for
confusion later if you end up working without it. Here's one that's popular,
lightweight, and helpful in my experience:

[https://necolas.github.io/normalize.css/](https://necolas.github.io/normalize.css/)

~~~
mikewhy
Definitely review multiple, because I find normalize.css to be pretty useless
as it doesn't set `box-sizing: border-box;`, or `img { max-width: 100%; }`

------
seanalltogether
I wish the author had gone a bit further into em vs rem. I'm reading other
articles on the topic but they're simply technical explanations and I'm still
not clear on what features of the page are best designed using em or rem.

~~~
chrismorgan
Just to mess with your mind: in media queries and in the root element’s font-
size declaration, em and rem mean the same thing, being the browser’s default
font size, which is 16px in most browsers by default, but customisable in some
browsers and different by default in some environments (e.g. I seem to recall
Kindle using 19px). I call this unit the “browser em”, or _bem_. No one else
really talks about it. One thing I _haven’t_ investigated and probably should:
does this unit depend on the _language_ the document is specified in? (Because
you can define different default fonts and sizes for different languages in at
least Firefox.)

~~~
LocalPCGuy
I would guess it does matter about the language, but likely because as the
language changes the font itself may actually change. And different fonts
would have different relative font sizes. But like you, I haven't investigated
it enough to make a definitive statement about it.

------
jb3689
CSS is such a weird abstraction. Who thinks in blocks and inline blocks? Who
thinks in paddings and margins? Floats, etc? I know these are more flexible,
but I've always found grid-based frameworks to be far more intuitive

~~~
Sharlin
CSS is a very reasonable abstraction for the job it was originally designed
for: layouting of mostly textual documents. As such it borrows its concepts
from the desktop publishing world. Margin and padding make absolute sense when
you think in terms of headings and paragraphs. Float is an established term
for having text flow by an image or other rectangular insertion. And so on.
You have to remember the context in which CSS was first conceived. The Web
looked quite different then.

~~~
runarberg
CSS has very much caught up for layouting and styling web applications. If you
don’t believe me, take a look at CSS grids.

~~~
Sharlin
Yes, I know. But the OP was talking about the classic stuff.

------
blue1
IIRC, _vertical_ margins collapse, horizontal margins do not

~~~
nimrody
That is correct
([https://codepen.io/nimrody/pen/dyGgBxW](https://codepen.io/nimrody/pen/dyGgBxW))

------
thrownaway954
here is the greatest thing i learned about css just last week:

.container { display: flex; align-items: flex-start; }

OMG!!! where have you been my whole life you little flex darling :)

you have no idea how much trouble and pain it is to align elements that are
table cells.

[https://css-tricks.com/almanac/properties/a/align-items/](https://css-
tricks.com/almanac/properties/a/align-items/)

------
ex3ndr
A lot of issues are simply solved by switching to flex.

------
christophilus
Margin collapse was new to me, and I’ve been doing this web thing a very long
time. Over all, that’s a great article. Nice and readable, too.

------
staycoolboy
I love reading these articles because it is a win-win:

1\. If I already know the tidbit, I give myself a pat on the back

2\. If I don't know the tidbit, yay, I learned something.

Someday I'll be 100% in the #1. What got me in this article "ch" size.

Fact: the heigh/width calculation has changed over the years. It is likely
this article captures the final method, let's hope so.

------
divan
\- One of the biggest traps for smart engineers is optimizing a thing that
shouldn't exist.

(c) Elon Musk, speaking about CSS (maybe)

------
minikomi
nth-child is really useful, and it's worth playing around to get a feel for
how multipliers and offsets work:

[https://css-tricks.com/examples/nth-child-tester/](https://css-
tricks.com/examples/nth-child-tester/)

eg. try 3n+1, 3n+2. 3n+3 and then different multipliers

------
bobbyz
CSS was designed to make sense in a context that is no longer relatable, same
with Git. This will never, ever happen if you'd designed your system to mimic
nature (unless global warming fundamentally changes it).

------
Brajeshwar
Wow! This is cool.

You got me at, "This was back in 1999, when we’d write things like <font
size="4" color="#000000"> and DHTML was a thing."

’twas the time when understanding the CSS Box-model was the graduation
opportunity to be part of the CSS-Pros.

------
larrik
> Notice how it’s the odd-numbered rows with a background? Given our selector
> (p:nth-child(even)), we might expect the even-numbered rows to be
> highlighted instead.

OR it counts rows from zero instead of 1, rather than all this about
siblings...

~~~
dhosek
That was my thinking as well.

------
jyriand
It’s amazing how software engineers can get things done without actually
knowing the tools they are using. CSS is one of these tools that i never
bothered to learn properly but instead hack it until it works as expected.

------
JacobSeated
Very good. I skimmed through it, since I am busy with some work.

But, I still code most things by hand. I only use WYSIWYG when I really have
to. Most often I find it faster and easier to create things with plain CSS.

------
Kiro
> But that won’t provide a great user experience, particularly for users who
> resize content at the browser level or zoom into content.

What browsers zoom dynamically nowadays? When is this actually an issue?

~~~
Kiro
What I mean is that browsers used to zoom in a way where all the texts were
automatically resized but nowadays the zoom works pixel-by-pixel, removing
this issue.

------
steve_adams_86
I’ve always thought of ch as a unit intended for monospaced fonts or languages
with monospaced characters. Does anyone know of any other practical uses?

~~~
memco
I personally feel it’s a good spacer between labels and form controls, icons
and text and can also be useful for other inline-like elements that should
have a natural spacing. Another possible use is in setting min and max widths
for content areas where ideal line-length for comfort of reading is considered
important.

------
bouncycastle
These would be great interview questions!

"So, you've been doing CSS since 1999. Please tell me how the width/height of
a box is calculated?"

~~~
Izkata
Me: "In which browser?"

~~~
bouncycastle
Ahh, yes.. who remembers "Quirksmode"?

Sadly, everything has to follow Webkit these days...

------
have_faith
> block elements expand horizontally to take up a whole line (like a heading).

Unless of course you set an input to display: block....

~~~
runarberg
Or anything for that matter with a non auto `width` other then `100%`.

------
baxtr
Side note: that’s a great marketing headline!

------
christiansakai
Very nice. I know most of these but then occasionally forget, this website is
a good reminder.

------
gklefnbkon
People really didn't know this? To be clear, I'm not criticizing anyone for
not knowing this stuff, as nobody can be expected to know everything (and
everyone was a beginner at one time). I'm just surprised that within this
community, where a lot of us are employed to build websites, that the basics
of CSS are still a mystery to so many of us. And I don't think that's the
fault of any individual. But clearly our industry has a problem.

Granted, if you spend most of your time on the backend, and only dabble in CSS
a little bit, or you're new to web development, it's completely understandable
to be fuzzy on the specifics of CSS. But that doesn't explain all the comments
from designers and front end people. So what's going on?

One possibility is that CSS is too difficult. Maybe? It certainly has it's
flaws. And it was harder to use in the past. But I don't think there's a huge
learning curve to understanding the difference between padding and margin, or
between block and inline elements, is there? Don't we do that sort of thing in
Word documents regularly?

Another possibility, then, is that the mental model of a document doesn't
match the designer's expectations. But I don't think this alone explains why
so many of us struggle with CSS. It's true that many of us are trying to make
applications on a platform meant for documents. It's also true that magazine-
style page layouts aren't a natural fit for a Word-like model of document
editing. But the features described in this article don't seem related to that
discrepancy - I can't see how ignorance about nth child or rem units relates
to the mental model of documents.

Here's what I think is happening: We spend too much time building new tools
and not enough time learning the tools we have. I've seen this with javascript
as well. There were some recent posts here about vanilla javascript, and
comments from React developers were surprised by some of the things JS could
do on it's own. Now React has it's place of course, just like how CSS
frameworks have their place. But I see a lot of people using these things as a
boilerplate, instead of using them where appropriate. And thus, we don't take
the time to learn how to do stuff with just HTML, CSS, and JS.

And granted, I don't think everyone needs to know that, just like how not
everyone needs to know assembly. But if not enough people understand what's
going underneath the hood, then the default response to any limitation is
"abstract more" and everything grows more and more bloated.

I'm not sure how we solve this. I suspect the time pressures of our industries
incentivize building things quickly, which leads to this problem. Another
possibility is that the browsers take too long to adopt new standards, which
leads people to seek out workarounds.

Has anyone here thought about this? Any ideas on what we should do? I think
the linked article is a good start. The explanations of CSS properties is very
clear, and I like the examples.

~~~
runarberg
I think the industry has an attitude problem towards the front end stack. HTML
and CSS is not what programmers do. Nobody takes the time to learn it,
everybody neglects it, managers hand it over to their newest junior developer,
project managers are happy as long as it looks shiny, bootcamps don’t teach it
properly, curriculums don’t teach it properly. In the end we have a bunch of
people that don’t know anything about the craft, that accept poor
craftsmanship as an industry standard.

I had a conversation about this with my partner—who is a woodworker—this
morning after reading this thread. I explained my perception of the status of
front-end within our industry as such:

It’s as if woodworking and carpentry were synonymous. There are woodworkers
that do cabinetry, but all of them learned carpentry. At most they took a
single course on cabinetry, but that course probably used outdated methods,
tools designed for carpentry, and the teacher them self has build a couple of
chairs and a few tables in the past. Most of the people new to the field of
cabinetry would come for bootcamps that last for maybe a month where they had
to learn woodworking from scratch. Good furniture makers are only expected to
be good at woodworking in general. Master carpenters are often expected to be
able to finish—or at least manage—furniture projects at their job.

You can imagine the sloppy craftsmanship you would see in the furniture
building industry if that were the case. And yet, as tech workers, here we
are.

------
HungryHarold
Nice article. A few of those tripped me up in the past also

------
z3t4
Specificity and cascade.

------
fk6aaa545c
My #1 thing about CSS - it's OK to use tables ("display: table" to be exact).

------
daiyanze
Hi, all! I'm author on pitayan.com. It's about front end development.

Link: [https://pitayan.com](https://pitayan.com)

