23 ms·
Things I wish I’d known about CSS
- divan 6y ago- One of the biggest traps for smart engineers is optimizing a thing that shouldn't exist. (c) Elon Musk, speaking about CSS (maybe)
- continuational 6y ago> 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 6y ago>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 6y agoThe 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 6y agoThe 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.
- continuational 6y agoOk, I can kinda see the value of that - e.g. if you put a "tag button" inside some text, it will have the right size in relation to that text.
- Izkata 6y agoThere's no date on the article, and this was the entry that made me wonder if it's 5+ years old, back when text zoom was more prevalent. When full zoom became the default, em/rem became less necessary, and at least to me appear to be falling out of favor as extra unnecessary complexity. (Quick edit: Mentioned but not really given much focus is that em/rem can be used on, say, image width and margin, as well - making it adjustable in a text-zoom world. That's mainly what I have in mind here.) (Even aside from affecting non-text, in the newly popular component-oriented design, you typically don't want relative font sizing to leak between components.)
- rimliu 6y ago"Relative" and "Absolute" have their own definitions and by that definition "px" is indeed an absolute unit.
- matsemann 6y agoNot anymore, as most px units now is based on a reference px, a size determined based on screen density and viewing distance. That's why something rendered at 600px on an iphone takes almost all the width, even though the screen has more than double that in pixels. And when zooming, the reference px is zoomed. So the old reason for not using px and instead use rem doesn't apply. https://developer.mozilla.org/en-US/docs/Glossary/CSS_pixel https://developer.mozilla.org/en-US/docs/Glossary/CSS_pixel
- wackget 6y agoYeah I came here to ask this. Using relative units for layout seems like a terrible idea. If you want to make your text a little bigger, your entire layout changes too. That's fine if it's something like text padding or paragraph margins, but stuff like border width, or dimensions of boxes? That seems weird. Browsers have been able to zoom pixel widths for years.
- maweki 6y agoI 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.
- yakshaving_jgt 6y agoCached URL since the server is apparently over capacity: 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 https://webcache.googleusercontent.com/search?q=cache:jcSTVF...
- rapnie 6y agoNow on http://archive.is/AiECQ http://archive.is/AiECQ
- peter_retief 6y agoThanks, clearly many people want to have a look.
- blue1 6y agoIIRC, vertical margins collapse, horizontal margins do not
- nimrody 6y agoThat is correct (https://codepen.io/nimrody/pen/dyGgBxW https://codepen.io/nimrody/pen/dyGgBxW)
- steve_adams_86 6y agoI’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 6y agoI 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.
- runarberg 6y agoYes. A good column width or grid card inline-sizes is between 30ch and 45ch, generally you don’t want text to exceed 90ch. These numbers come from print design for magazine or journal layouts. In general the `ch` unit is perfect for defining the inline-size of text containers.
- ChrisMarshallNY 6y agoThat’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-to-specificity/ https://littlegreenviper.com/miscellany/stylist/introduction...
- xanathar 6y agoEnds up to a page saying "The page you requested does not exist". ...which kinda reflects "things I wish about CSS", so 10/10.
- harshamv22 6y agoIts loading here. Try again :-)
- xanathar 6y agoI know, I retried before and it worked. But "it works differently every time I try" wouldn't have made a good CSS joke. Oh, wait.
- zero_iq 6y agoPage 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 6y agoSame here (and same browser/OS), it seems like some font is missing?
- baxtr 6y agoSide note: that’s a great marketing headline!
- swyx 6y agofor 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.
- geewee 6y agoThis 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.
- paozac 6y agoUseful 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.
- onion2k 6y agoJust use flexbox (and grid if you need to control both dimensions at once). You can ignore all of the old ways of doing layout. Flexbox is supported back to IE11.
- tzs 6y agoAs an occasional CSS user, I second that. Every time I have had to use CSS for anything more complicated than diddling item appearance has led to a lot of time on Stack Overflow trying to find answers to questions like "why did my height change work on this element but not that element?" or "how can I center this text vertically in this space?". I don't use CSS frequently enough to not forget these things by the next time I need it. I'll still probably forget parts of Flexbox between the times I need to use CSS, but it will be things like forgetting like what spacing modes are available, which is easy to quickly look up. Flexbox is now my turtle [1]. Well flexbox and grid. [1] https://en.wikipedia.org/wiki/Turtles_all_the_way_down https://en.wikipedia.org/wiki/Turtles_all_the_way_down
- Someone1234 6y ago> Flexbox is supported back to IE11. Nope. An incompatible and broken version of Flexbox is supported in IE11. Therefore, layouts look completely different (and broken) when rendered in it. Only people who recommend Flexbox in IE11 haven't tried using it in IE11. I might via a library that did the heavy lifting for me, but there's just too many bugs to recommend anyone write Flexbox and expect it to just work -- it won't/doesn't. PS - I'd link all the IE11 Flexbox bugs but Microsoft took them offline with Microsoft Connect's retirement.
- 6y ago
- seanalltogether 6y agoI 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.
- pabue 6y agoGenerally you want to use rem for setting the font-size of the elements and to controll overall spacing. em is often used for the padding of elements. For example buttons that exist in different sizes.
- agloeregrets 6y agoFrom an overall perspective, em: unit based on the font size of the element it is querying. rem: unit based on the font size of the body element. rem is helpful if you want to make an entire page scale uniformly if you change the base font size (imagine accessibility settings) while keeping the same proportions with padding to font size. em is great for things like buttons where you may want to make one class for `button.cool-button{ padding: 1em; font-size: 14px; &.xl{ font-size: 20px; }}` and then you can change the font size by setting the `.xl` Class on that button and the padding will go from 14px to 20px. One button, shared proportions.
- chrismorgan 6y agoCorrection: rem is relative to the font size of the root element, which in HTML is <html>, not <body>.
- chrismorgan 6y agoJust 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.)
- andi999 6y agoAnybody 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 6y agoNot 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 6y agohttps://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.
- nanna 6y agoCan't recommend Andy Bell and Heydon Pickering's Everyday Layout enough. It's a wonderful resource for learning (and re-learning) contemporary best practice CSS. https://every-layout.dev/ https://every-layout.dev/
- httpsterio 6y agoI have every book written by Heydon and am currently doing Andy's 11ty course. They're both stellar teachers and some of the most knowledgeable programmers when it comes to HTML and CSS. Every Layout is amazing. Strong recommend.
- lrmunoz 6y agoBest resource I've found to learn the foundation of HTML/CSS is Shay Howe's guides [1]. I think it doesn't cover Flexbox and more advanced layouts, but it's totally worth a read. I still go back to it as reference from time to time. [1] https://learn.shayhowe.com/ https://learn.shayhowe.com/
- superasn 6y agoThis 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)
- minikomi 6y agonth-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
- hellofunk 6y agoYikes. 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 6y agoSix 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.
- christophilus 6y agoThat is going to happen. Big corporations are finally waking up to 1st class remote work, and that’s the gateway to lower US wages. I say this as a remote worker, and a huge fan of remote work. But I do think the high US salaries are going to mean revert a bit.
- nanna 6y agoSounds to me like tech workers in the US should join a union, and quick!
- indigochill 6y agoNow, admittedly I'm a skeptic of unions by default (in my view they're mostly just another layer of bureaucracy/waste), but isn't unionization of tech workers in the US the quickest way to make themselves even less desirable? Why hire a US union member when you can hire an Eastern European who both works for peanuts and doesn't have union hang-ups? (Admittedly outsourcing has its own problems, especially when there are language/cultural barriers)
- amanzi 6y agoThis 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/
- z3t4 6y agoSpecificity and cascade.
- acqq 6y agoApart 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.
- christophilus 6y agoMargin 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.
- chrisweekly 6y agoIf 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.
- Kiro 6y agoThe ; in your link sends me to about:blank#blocked.
- quietbritishjim 6y agoFor the benefit of others: https://every-layout.dev https://every-layout.dev
- chrisweekly 6y agoThanks! Wish I'd caught it in time to fix my 1st comment.
- randompwd 6y agoTo save clicks, it's $100, just covers page layouts.
- chrisweekly 6y agoThat'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 6y agonot 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
- Kiro 6y ago> 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 6y agoWhat 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.
- wruza 6y agoGuys 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 6y agoI 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 6y ago> 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 6y ago> 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 6y ago
- techbubble 6y agoThis 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/1282045825082781696 https://twitter.com/thecoffeejesus/status/128204582508278169... https://twitter.com/alyd789/status/1271200537988431873 https://twitter.com/alyd789/status/1271200537988431873
- peruvian 6y agoA lot of people make games or fun projects for #100DaysOfCode when their job might be updating a CRUD MVC app using Y framework. I think as long as it puts them in the "coding" mindset it's worthwhile.
- techbubble 6y agoI agree with that 100% — if it isn't fun, it's work. And if you build enough knowledge about how CSS works in general, when it comes to implementing specific layout or responsive design techniques you have a good understanding of the basics to build upon.
- umaar 6y agoI 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/
- daiyanze 6y agoHi, all! I'm author on pitayan.com. It's about front end development. Link: https://pitayan.com https://pitayan.com
- gorgoiler 6y agoIt 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.
- blauditore 6y ago> but I’ve rarely seen a high quality PDF renderer What exactly do you mean by this? That HTML-to-PDF converters mess up the layout, or similar? You might be aware of this, but it's still worth pointing out that you can specify a different stylesheet for the print version of an HTML page than the default one. I've used this in the past for websites where the customer wanted to use a product description page directly for generating PDFs, without having to do the work twice. We also used some Java-based HTML-to-PDF renderer, which was not perfect but had full support of CSS 2.1 and some support of CSS 3 (and this was several years ago). I think the library was Flying Saucer (based on itext).
- mkayokay 6y agoI 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 6y agoYes, I was going to recommend WeasyPrint as well.
- PetahNZ 6y agoAlthough not exactly what you want, my day job is basically implementing systems that take SVG's produced in design tools, pipe them through to a customer UI for designing print books, posters etc, then renders high res images server side with Chrome headless and finally sending them off to the printer. SVG does a great job, but still requires a lot of coding for laying out the text, line breaks, pages, etc.
- jyriand 6y agoIt’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.
- bouncycastle 6y agoThese 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 6y agoMe: "In which browser?"
- bouncycastle 6y agoAhh, yes.. who remembers "Quirksmode"? Sadly, everything has to follow Webkit these days...
- Brajeshwar 6y agoWow! 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.
- jitendrac 6y agoThat 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 6y agoHave 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 6y ago> 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 6y agoThanks, froggy was on front page of HN so I knew it for sure, grid garden is new one for me.
- jitendrac 6y agoyes, I really did play with it multiple times. Its just sometimes I require more revisions.
- IggleSniggle 6y agoI felt the totally opposite about grid. I spent a little time learning it, and now EVERYTHING is easy (except for things that aren't, of course)
- aliswe 6y agoA 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.
- interactivecode 6y agoMost designs and typography are referenced of a basic unit, the body font size. Setting that size once and using rem makes it easier to build out and change.
- mellow2020 6y agoUsing relative units makes it very easy to scale things. If you use pixels or other absolute units everywhere, you'd have to edit every instance of that, which can range from an annoying chore to being completely unfeasible. https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Values_and_units https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_...
- partyboat1586 6y agoI just use rem when it needs to be relative to the text size, px everywhere else. This way when you scale the text for accessibility you don't get any clipping.
- rob74 6y agoIt'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...
- jFriedensreich 6y agostrongly agree. this article sums the current state up perfectly: https://medium.com/hackernoon/rems-and-ems-and-why-you-probably-dont-need-them-664b9ce1e09f https://medium.com/hackernoon/rems-and-ems-and-why-you-proba...
- Phillips126 6y agoGood 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.
- christiansakai 6y agoVery nice. I know most of these but then occasionally forget, this website is a good reminder.
- pansa2 6y ago> 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 6y agoIt 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 6y agoDefinitely 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%; }`
- LocalPCGuy 6y agoI prefer a combination of reset/normalize, but because of that I agree with your statement re: learning from what you are using. Then you can make informed choices about how you are using those things.
- earthboundkid 6y agoYes. There are different philosophies for how to write CSS, but assuming you're aiming at something like BEM (Block, Element, Modifier) style, it's typical to start with a reset of the raw elements into a standard form, and then follow that with the CSS for you class components, and finally some !important override utilities. Basically all the CSS philosophies agree that you should never use #id selectors at all and use of element selectors should be (mostly) limited to resets.
- rimliu 6y ago
- k__ 6y agoIt 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 6y agoCobbler 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.
- thrownaway954 6y agohere 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/
- dzink 6y ago20 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.
- larrik 6y ago> 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 6y agoThat was my thinking as well.
- deleted 6y ago[deleted]
- jb3689 6y agoCSS 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
- tenuousemphasis 6y agoYou can construct a grid based system based on a block system, but wouldn't the reverse be much more difficult?
- robertoandred 6y agoAn off-the-shelf grid system is too inflexible, and you spend more time customizing it or fighting it to get the result you need than you would have just building what you need.
- Sharlin 6y agoCSS 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.
- IggleSniggle 6y agoDear lord it's 2020 CSS has its own grid system, it's CSS Grid, and it's both easier to understand and more flexible than adopting the old frameworks. It also has variables, pseudo-selectors (which, like with html elements, you can invent new ones to suit your purposes), and more.
- leephillips 6y agoI 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 6y agoIf 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 6y agoI’m confused by your reply. Did your eye skip over the word “not” in my comment?
- chrismorgan 6y agoSorry, you are correct. Drop the final parenthetical, then, but I stand by the rest.
- leephillips 6y agoYes, 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.
- have_faith 6y ago> block elements expand horizontally to take up a whole line (like a heading). Unless of course you set an input to display: block....
- runarberg 6y agoOr anything for that matter with a non auto `width` other then `100%`.
- JacobSeated 6y agoVery 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.
- gklefnbkon 6y agoPeople 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.
- staycoolboy 6y agoI 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.
- c-smile 6y agoThere 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.
- c-smile 6y agoI 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 6y agoDon’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 6y agoThat 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
- ex3ndr 6y agoA lot of issues are simply solved by switching to flex.
- jraph 6y agoAn 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 6y agoTo 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-inside https://developer.mozilla.org/en-US/docs/Web/CSS/display-ins...
- jraph 6y agoAh 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 6y agoI 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
- cookiengineer 6y agoMeanwhile, 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 6y agoI'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/client/gui/box/init.lua#L158 https://github.com/Planimeter/grid-sdk/blob/master/engine/cl... [2]: https://www.w3.org/TR/css-flexbox-1/#resolve-flexible-lengths https://www.w3.org/TR/css-flexbox-1/#resolve-flexible-length... [3]: https://github.com/facebook/yoga/blob/master/yoga/Yoga.cpp#L2382 https://github.com/facebook/yoga/blob/master/yoga/Yoga.cpp#L... [4]: https://docs.microsoft.com/en-us/dotnet/framework/winforms/advanced/why-transformation-order-is-significant https://docs.microsoft.com/en-us/dotnet/framework/winforms/a...
- HungryHarold 6y agoNice article. A few of those tripped me up in the past also
- joann56 6y agoIf you are really in need of getting a best result about your credit report am using this opportunity to introduce you to this Notorious, Wonderful and Bankruptcy Problems Solver Hacker. You will never get to know until you give him a trying space to prove him self and let his job speak, He help me hack my FICO score and also help me with some adjustment on my Report too. all you need is e-mail EAGLESPYHACKER@GMAIL.COM you’ll be guided to your success destination.
- fk6aaa545c 6y agoMy #1 thing about CSS - it's OK to use tables ("display: table" to be exact).
- bobbyz 6y agoCSS 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).