Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
CSS Tips (markodenic.com)
556 points by qubitcoder on April 26, 2021 | hide | past | favorite | 157 comments


> Easily center anything, horizontally and vertically, with 3 lines of CSS

This can actually be done with 2 lines now!

  .center {
    display: grid;
    place-items: center;
  }


It took us 20 years for a simple way to center items vertically. I mean, COME ON.


It will take another 20 years for people to stop complaining about it retroactively.


It will take more another 20 years for people to stop commenting about this.


Lets take some time to remember table layouts and blank.gif


No need to remember, look at the source of this website.


HN is certainly an appropriate place to remember those. Although, here it’s s.gif.

https://news.ycombinator.com/s.gif


And frames. And tables with iframes. And, indeed, 1x1.gifs. Fun times!


And rounded corners!


Yep, it makes no sense, especially since

  <td valign="middle">
worked flawlessly.

Of course maybe there is some good explanation... I certainly never contributed to the CSS spec.


You can do the similar in pure CSS with:

   foo { display: table-cell; vertical-align: middle; }
And it has also worked a lot longer than the flex-approach. But now when flex is available it seem the more appropriate tool for the job.


For what I know the main argument against td is that tables are for data, not for layout.


We generally don't remember how bad the internet search was before Google came along, but it was really, really bad. I have zero evidence but I'm pretty sure that some time ago some industry heavyweights asked themselves "Why the search in the apps works fine but the internet search is broken? Is it because the apps have the intimate knowledge of the structure of their data and the search engines don't? Shouldn't we convey to them that structure?". Thus the idea of the Semantic Web was born, using tables for layout became cardinal sin and we entered the long Dark Age of trying to wrestle floats into doing something they never could really do. Then along came Google and made it all obsolete, but the priests of Semantic Web had too much fun torturing mere mortals that they stretched the Dark Age up until the adoption of the Grid Layout. When I hear someone saying that tables are for data and should not be used for layout I want to punch them. Yes, I've been that bitter for two decades.


Haha, ya, in the end, tables are still the simplest to reason about when it comes to layout! I kept using them long past when we weren't supposed to since the whole float thing was a mess and compatibility was still a big issue.

While it's a ton of markup, tables are build upon a few easy-to-remember concepts and you can do anything (including vertically align without googling!). I'm still constantly looking up flex and grid rules.

That said, I did move on.


Right, I’m not arguing for using it, I’m pointing out that easy vertical alignment has existed in some form since the 90s, so why did it take so long for a semantic version to make it into CSS? (ie, not the display:table version in the sibling comment)


What do you mean "semantic"? CSS is for presentation, not semantics.


Like, before the best way to do it in CSS was the change the display type of an element to a “table cell” even if it’s not a part of a table. I mean, changing it to “flex” or “grid” doesn’t make much sense either, really, I rather just have a box with vertically aligned content. I dunno, am I using the word semantic wrong?


OK I agree it was not intuitive to change the display-type to table-cell just in order to vertically center content. It basically mirrored how you would would vertically center in presentational HTML, except you didn't need to misuse the semantics of the table element (which is why I was initially confused by your comment about semantics.)

The flex-box approach is the most intuitive in my opinion. The flex display-type basically means you want to distribute the area of a box among its immediate child elements, and control how the children and aligned relative to the container and each other. Centering is naturally part of this.

Using grid is IMHO less intuitive, since a grid with a single cell seem just as much a hack as a table with a single cell.


Yep, I do agree that of any of them, flex makes the most sense from a language standpoint.


It took half of that. display:table-* have been available for more than ten years already.


that's because half the planet's brain are trying to make printers work


this is my first time seeing the `place-items` property. at first glance I have no idea how it relates to `align-items` or `justify-content`. Feels like the grid API is getting a bit too cumbersome but maybe its just me.


I am a backend engineer, but I need to do work on UI for my personal project. This guide from Rachel Andrew on CSS grid and flexbox is superb. She will take you from a n00b to a total Grid Ninja.

https://www.smashingmagazine.com/2020/01/understanding-css-g...


It's shorthand: https://developer.mozilla.org/en-US/docs/Web/CSS/place-items

MDN also has a list of shorthand properties if someone didn't know what 'shorthand property' really meant: https://developer.mozilla.org/en-US/docs/Web/CSS/Shorthand_p...

But yeah, the discoverability or suggestion-to-refactor-something-to-shorthand is typically non-existent in CSS. Lists like these are really the only way I discover CSS stuff.


May I suggest trying out webstorm or any other JetBrains IDE?

They have the best CSS completion I’ve ever seen, and it includes live (and cached) mdn documentation for each rule. It also suggests shorthand collapses as a feature


place-items is just a shorthand property that takes 2 arguments. The first argument sets the align-items value and the second argument sets the justify-content value. If only one argument is provided (as in this example), it sets both align-items and justify-content to that value.


Actually, this is technically incorrect. It doesn't set justify-content, it sets justify-items. This is why it works with grid, and not flexbox

Source: https://developer.mozilla.org/en-US/docs/Web/CSS/place-items

I think there's a lot of confusion for most people between justify-content/justify-items and align-content/align-items


Ah, I see. Thanks!


If you use PostCSS, postcss-preset-env[1] is pretty neat for reading up on the latest features. E.g. here is the place properties feature[2].

1: https://preset-env.cssdb.org/ 2: https://preset-env.cssdb.org/features#place-properties


Don't forget align-content and justify-items !


IMO not worth it for the loss of compatibility, since flexbox is just as easy.


Grid has extremely broad support.

https://caniuse.com/css-grid

The notable exception is IE 11…though even then, with a bit of autoprefixer magic, you may be able to use this.


or you could just use flexbox to do the exact same thing and have a superset of that extremely broad support, including ie11 without having to rely on any kind of magic.

https://caniuse.com/flexbox

I do use grid when I need it, but I don't see the point of using grid in places where flexbox will do. Granted this is on the verge of not mattering at all anymore, but I just don't see the point in using something less compatible when you don't have to.


I want to learn grid, and I keep waiting to be given a layout I can't implement in flexbox as an excuse. It's been years of waiting through multiple jobs.


I like grid because it eliminates the need for any elements that exist purely for layout. This makes markup cleaner which makes it easier to change in the future.

But as I stated in elsewhere in this thread, grid is not a replacement for flexbox. There is overlap, they both have their strengths.


the one thing i couldn't do with flexbox where I had to use grid was a sidebar that was being rearranged responsively, part of it below the main content, and part of it above. but yeah, most of the time flexbox + order can get you quite far


An acceptable subset of CSS Grid works on IE11. And if you use autoprefixer, 99% of the time would work out of the box.


I have not found this to be true at all. It's far less than 99%, and would require double checking all your work in IE11 to make sure it works. I tried some basic layouts and found that a lot of unexpected things occurred. If you're supporting IE11, CSS grid isn't worth it.


IE compatibility is increasingly rare. Grid is supported by 95% of all browsers globally. If your target group is any narrower, or if centering the content doesn’t break the page and you aren’t shy of serving a weird looking layout to people with old browsers, there is no reason not to use grid.


there is no reason not to use flexbox if all you want to do is center something. and that sentence doesn't even need any additional qualifiers.


What browser are you even worried about at this point? IE isn't even supported by microsoft any more.


That is not true[0].

[0]: https://death-to-ie11.com/


It is in the sense that they produce websites that no longer work properly with IE.


Grid is way better than flexbox. All hail CSS-Grid.


Grid is not a replacement for Flexbox, it compliments it. Flexbox excels when you are only concerned with one dimension, grid excels when you're concerned with two (ie, a grid!) And yes, there is overlap.


They have many overlapping capabilities, but there are things flexbox can do which grid cannot. For instance, flexbox can wrap with dynamically sized children.


Got a citation for this?

I’ve seen this said, and for the life of me, I can’t find an actual reference for it.


Citation: Purely subjective personal experience / opinion.

At least it’s first-hand.


They solve different problems.


In general: Flex is for flowing content, grid is for structured. You can do some awesome wrapping with flex that is impossible with grid. Also `margin-inline-start: auto` is pretty rad using flex, although you can do something similar with `justify-self` with grid.

A good use case for flex would be a list of tags, that need to wrap.


Also harder to learn.


I was going to say: "let's now wait 10 years for it to be usable", but then I went to canisuse and wow: 96.01% of availability!

https://caniuse.com/?search=grid


Some noteworthy caveats from my experience with CSS grids:

- Particularly in Firefox they are much slower. When grids start to pile up on a page, performance goes down the drain

- Implicit row-sizing is not really a thing in Safari or iOS -> https://stackoverflow.com/questions/44770074/css-grid-row-he...

Quote from that SO post: "This is not a Safari bug. It's just a different interpretation of the spec.

When dealing with percentage heights, some browsers (like Safari) adhere to the traditional interpretation of the spec, which requires a defined height on the parent.

In other words, a percentage height on an in-flow element will be recognized only when the parent has a defined height.

Some browsers, such as Chrome and Firefox, have moved past this interpretation and now accept flex and grid heights as an adequate parent reference for a child with a percentage height.

But Safari is stuck in the past. This doesn't mean it's wrong, invalid or a bug."

Just worth noting, as I had a lot of fun with that one.


I'd argue that `place-content: center` is better than `place-items: center` as it would handle multiple child elements in a way most people would expect from a simple centering snippet.

place-content will position all the children to the center, which is generally what's desired here.

place-items, would make each child element center itself within its own grid square


Haven't people been doing this in two lines already?

  .center {
    display: table-cell;
    vertical-align: center;
  }


  CENTER{LINE-HEIGHT:100VH}
https://jsfiddle.net/pnyr1u8d/

actually, neither of your versions work without specifying a document height. (or outer container)

  .center {
    display: grid;
    place-items: center;
  }
https://jsfiddle.net/a67gzsjf/

something like this would work

https://jsfiddle.net/a67gzsjf/2/


I'd love to see a "Can-I-use" browser extension when looking at articles like this.

Occasionally a project requires IE 10/11 support (state government work) and it's such a shame to get excited about an impossible CSS approach.


I'd love to see a "Can-I-use" browser extension when looking at articles like this.

I agree, though what I would find really helpful is not just can-i-use but should-i-use, taking into account not only feature availability but also quality of implementation. Even if a feature is theoretically supported in all major browsers, it’s not much use for a production site or app if what you actually see on screen in at least one of those browsers looks terrible, for example because of bad anti-aliasing or colour handling or animation calculations. I’ve been building new UI/design systems from scratch for a couple of projects recently, and it’s amazing how often that still happens, even with popular CSS features used to implement relatively simple effects.


caniuse.com reports whether something is too buggy to the point of being unusable in a different color, and has footnotes for whether something has some quirks/caveats but is otherwise usable


That’s true up to a point, but caniuse and I sometimes have different interpretations of what is too buggy to be usable. Rasterising vector formats and working with colour seem to be two common triggers for poor rendering, with extra chances for visible glitches if they are used in combination and a bonus if animation is involved as well.


IE 10 has no TLS 1.2 support. I think you can now safely drop it.


What's everyone's opinion on simply forcing users of IE11 to upgrade / use a different browser?

I understand that one should aim for a certain level of backward compatibility, but when does the time come to drop IE11 support for good?

Especially as a smaller webdev-shop, how would one even come up with the resources to maintain that level of compatibility? Eventually there is a trade-off where one may end up losing a (hopefully reasonably small) percentage of customers in exchange for focusing on the experience of those customers who are more up to date, but it's a tricky decision to make.


IMHO totally depends on what you are doing and who your users are. Generally going for graceful degradation should keep a lot of stuff usable for outdated browsers, even if not full fidelity/pretty, and that often should be enough. If you have lots of IE11 users for whatever reason (i.e. I believe in some countries rates are a lot higher) it might be worth the effort to make it better for them. If you ship an internal app for a company that rolls out a newer standard browser everywhere, target that.


Basically none of this supports IE 10/11 (flexbox one works, calc works, and that's probably about it). Chances are if you see a cool new trick, it doesn't support IE 11.


Seems that Microsoft is sunsetting IE11 [1], I wonder if that would nudge the world towards less IE.

[1] https://techcommunity.microsoft.com/t5/microsoft-365-blog/mi...


> * Cursors Did you know that you can use your own image, or even emoji as a cursor?

This was the very first bit of CSS I ever learned thanks to my first internet friend, Tom.


I was rather taken by Tom's introduction to scrolling text by way of the marquee tag.


The tooltip example sounds neat, but that approach will run into problems when your tooltips need to appear near the edges of the viewport.

Libraries like popper.js (no affiliation) exist to solve this specific problem.


Popper.js is required for tooltips in Bootstrap.


I learned something. But would have been better (easier) if the snippets of code only included the css in question and not fonts/backgrounds etc. I had to read each a few times to find the relevant bits.


Okay, the ":target" psuedo class just blew my mind. Not necessarily for modals (which I don't particularly like) but I can think of a lot of other uses. Edit - Apparently it's been around for several years. Not sure how I missed this.


Likewise! That's actually the reason I submitted the article.


I used it several years ago to create deep links to a list of audio files on the homepage of a site I built. By default the controls were hidden, but if you clicked one of the titles in the list it would show the controls and update the url so you could share a link to that specific item with no JS required.


HTML tip: provide an ID to headers so you can link to them directly! :-) Also, provide an anchor so users can just copy the link and not have to inspect the html or use an extension to link to your headers.


This is a nice list of things that are actually useful and surprisingly straightforward to do.

Considering how many people (myself included) consider CSS a veritable minefield, I love seeing examples like this.


Scrollbar styling is arguably a lot easier using the standard CSS-scrollbars-level-1[1]

    scrollbar-color: rebeccapurple gold;
    scrollbar-width: thin;
As a bonus it works in firefox.

1: https://drafts.csswg.org/css-scrollbars-1/


I thought I knew CSS pretty well, but

  position: sticky
is a new one for me.


Sticky headers suffer from one glaring issue: If the page loads to an #anchor position, the sticky header covers up the anchor. Fix:

  window.onload = function()
  {
   var titlebarfixcoverfunction = function()
   {
    if (location.hash.indexOf('#') > -1)
    {
     var titlebar = document.getElementById('title');
     window.scrollBy(0, -titlebar.offsetHeight);
    }
   };
   titlebarfixcoverfunction();
   window.addEventListener('hashchange', titlebarfixcoverfunction);
  }


You don't even need JS to fix the target scroll: https://stackoverflow.com/questions/10732690/offsetting-an-h...


That only works when you set the height explicitly.


Yeah, but have a little problem. What happen when the anchored item have visible text ?


Or just use the css property scroll-margin.


This only works with explicitly set heights. If you don't know the header's height, this won't work.


Unfortunately not supported by Safari.


Follow-up reading material... IntersectionObserver: https://developers.google.com/web/updates/2017/09/sticky-hea...


I've used it for a few things and once you go beyond the basic examples, it's the wild west. But if you manage to make it work, some things like pricing tables where a section is sticky to the top until the next one pushes it upward, it's really neat.


Here's a really useful thing to bookmark:

javascript:(function()%7B(function%20()%20%7Bvar%20i%2C%20elements%20%3D%20document.querySelectorAll('body%20*')%3Bfor%20(i%20%3D%200%3B%20i%20%3C%20elements.length%3B%20i%2B%2B)%20%7Bif%20(getComputedStyle(elements%5Bi%5D).position%20%3D%3D%3D%20'fixed')%20%7Belements%5Bi%5D.parentNode.removeChild(elements%5Bi%5D)%3B%7D%7D%7D)()%7D)()

Click the bookmark and sticky things disappear. Some websites are horrific with how much screen space they take up with sticyky banners. That also of course breaks some sites.


Interesting. Now does any browser actually support pgup/pgdown properly? Every time I run across a website that does this it annoys me that paging down doesn't properly account for the height of the stickied header making pgup/pgdown unusable.


The browser can't determine this statically (imagine trying to distinguish between a sticky header that takes up the entire width of the viewport, and a sticky sidebar that doesn't intersect the content at all), but page authors can use the scroll-padding variable to fix this! See https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-padd... and https://css-tricks.com/fixed-headers-on-page-links-and-overl...


I was researching something similar recently (sticky elements covering anchor scrolling) and there’s a somwhat modern solution to that: https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-padd... . As usual with new tech though, doesn’t work in Safari (and hence all of iOS) for now. I wonder if the same property could be used to make pgup/pgdown/space work correctly.


It's fairly new in general and not widely supported yet:

https://caniuse.com/css-sticky


> It's fairly new in general

I used `position:sticky` in a productive website back in 2015, when it was already well-supported in Firefox. What's true is that Chrome only got support for it recently, and since Chrome == the internet nowadays, you will be forgiven for considering it new.


To me 2015 is new. I wrote my first lines of JS in 2001.


Your link actually shows that it's very widely supported by everything but IE, just with a long standing bug in Blink.


Exactly. Full support won't be there until all the marked issues are fixed.


Works on my iOS13 iPad, where there are 4-5 on that page that don’t.


Pretty neat. The scroll snapping makes creating a scrollable image carousel super easy.


Fantastic article. Learned some things. Well done, loved the read.

Surprisingly most of these have great browser support.


A good number of them either don’t work or are irrelevant on Safari/iPadOS.

That’s not to say this is a bad article; it’s not. It’s just that there is more to CSS than “here are some rules and ways of using them you might not have thought of”. That’s the real reason front-end dev and design is as difficult as it is.


What... Did you even read the article? This isn't true at all.

---

Supported Everywhere:

- Typing Effect (@keyframes)

- Drop Shadow

- Smooth Scrolling

- "center" (flexbox)

- Truncate Text (uses line-camp)

- Resize

- Modals (uses :target)

- calc

- Style Empty (:empty)

- Position Sticky (minus some table elements in old versions)

- Scoll Snap (partial support in even IE)

- Dynamic Tooltips (is just pseudo elements...)

- Caret color (except old IE)

- Fancy Text (uses background clip, so all but old IE)

---

Not Supported Everywhere:

- Cursors (mobile, obviously...)

- ::selection (mobile ignores)

- Custom Scrollbars

---

I think if you put it side-by-side like this you really see how inaccurate your comment is...


Yes, I read the article - via Safari on my 11” iPad Pro.

Things that work: - Typing Effect (@keyframes) - Drop Shadow - "center" (flexbox) - Truncate Text (uses line-camp) - Modals (uses :target) - calc - Style Empty (:empty) - Position Sticky - Scroll Snap - Dynamic Tooltips (when using touchpad) - Fancy Text

Things that don’t work: - Smooth Scrolling - Resize - Cursors (even when using the touchpad cursor) - ::selection (even using Safari in “Desktop mode”) - Custom Scrollbars

I could test due to not having a live example: - Caret color


Even custom scrollbars work everywhere with different prefixes[1]. It just needed a couple of extra (unprefixed) rules for the missing firefox support:

    .tile--custom-scrollbar {
      scrollbar-color: rebeccapurple gold;
      scrollbar-width: auto;
    }
1: https://caniuse.com/css-scrollbar


> Supported Everywhere

Let me guess, "Everywhere" is only the Chrome based, latest browsers?


Check the stats on caniuse and get back to me. These would be mostly supported everywhere, partially supported, or with prefixes.

The only argument being "but not on IE". Which, 100% of these work on almost all versions of Edge. Edge is provided side-by-side with Internet Explorer these days (mostly...).

Internet explorer market share is near zero. Also reminding you that these are just CSS properties (meaning fallbacks are dead-simple or it just looks/behaves boring-er and doesn't break anything).


The following did not work for me in IE:

- Drop shadow - Custom cursors - Smooth scrolling - Truncate text to a number of lines - Custom scrollbars - Sticky position - Scroll snap - Fancy text - The CodePen CSS button


IE usage is under 1% now. It's really only used by people for accessing specific legacy apps and internal websites. Microsoft is ending support for it.

There is no longer any reason developers building general-audience websites, web apps, or libraries should care about IE support. It's not part of the general conversation anymore.

You only need to cater to IE if you're a developer on one of those legacy sites, or maintain a library that has been around for so long it's still actively used by those legacy sites.


I understand that and I happen to be one of those developers that has a customer that requires IE to be supported. So I was interested in the behavior of the site under IE. My experience testing the site in IE was different than that of another poster, so I thought I would document it. I apologize for causing you whatever consternation prompted you to react in this way, it certainly wasn't my intent and wasn't anticipated.


It's really only used by people for accessing specific legacy apps and internal websites.

And healthcare. And government. And a lot of other non-Silicon Valley and non-hobby industries.


Those are the types of legacy apps and internal websites I was referring to.

What did you think I was talking about instead?


Safari user here: I didn't see any examples that didn't work.


I miss the push-button and border-triangle trick;)

https://pilabor.com/blog/tricks-you-might-not-know/html-and-...


Hmm the link has changed, here's the new one if anyone else is looking for it: https://pilabor.com/blog/2021/03/html-and-css-tricks/


That page also has some tips I didn't know.

> <a href="#!">

(don't jump to page top on click)


It isn't anything special like that, it's trying to jump to an element with id="!" but not finding one. Any gibberish after the # that doesn't match something on the page would work.


I stopped adding fancy stuff years ago after realizing browser compatibility has real consequences. :D


About a year ago I seriously considered rolling everything back on my homepage to HTML 2.0, given that was the last one with an actual RFC, though 4.01 had a decent specification.


Cool stuff, but wish there was a disclaimer saying many of the things here are Chrome-only. The target audience for this might not consider browser compatibility from the get-go and have to re-think their UI later.


I'm not sure what you mean; I just tested and all of the examples seem to work in Firefox. Many of them rely on features that have come out within the last couple years, but there's a big difference between "modern" and "Chrome-only".


Some of them are using webkit prefixes, and those only. So it's easy to think they won't work everywhere.

But some of those have been added as standard (with the webkit prefix for all browsers), like explained here: https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-lin...

Which of course is a consequence of it being widely used before it was a standard forcing other browsers to adopt..


Don't use their modal trick, it breaks accessibility.


Can you be more specific? What specific thing breaks? Screen readers?


It doesn't trap focus.


Also seems to play weird with the go back browser functionality


That custom scrollbar tip doesn't work very well in Firefox :)


Half these things should be avoided. Don't mess with scroll or scroll bars. If a user wants smooth scroll, they will enable it in their browser. Snappy scroll is unpredictable and disorienting.


How did I know this would be the top comment on HN?

There are legitimate uses for snap-scrolling, e.g. a horizontal carousel on mobile (or even desktop, depending on implementation), where you want swiping to swipe so the next item is in view.

Also, you said half these things should be avoided -- care to list the others? It seems like the theme of the post is "you don't need JavaScript to do this." If some functionality is rarely needed, but does have use cases, it's nice to know that it can be done in CSS without requiring JS (which would be clearly worse).


> There are legitimate uses for snap-scrolling

https://shouldiuseacarousel.com/

So... no, there isn't a legitimate use for snap-scrolling. Leave scrolling alone.


Oy. Yes there, are legit uses. A few straightforward examples:

1) You implementing something boards (like trello) on mobile. The well-established-in-all-the-apps-that-specialize-in-this behavior is snap scrolling.

2) Tiktok/stories/etc. When you scroll up or right, does it ever land you in between two stories? No. This is the exact behavior.

3) Presentations. Say you are building a presentation tool. The whole point is to define separate slides that are on screen one at a time. This is a very natural and appropriate use of this behavior.

So, yeah, carousels suck. But, this behavior is commonly used and useful in a lot of modern software.


That page is mostly about auto-rotating carousels. Don't do that.

It's also about making your home page a giant carousel, instead of showing multiple things vertically. Don't do that, either.

IMO, one great use for carousels is when you have a product catalog with a bunch of category sections, like Netflix. Each category gets a header, e.g. "Action" "Family" "Romance" "Horror" and each category is a horizontally scrolling list of products, with the next one on the list half-visible on the side, so it's clear that you can scroll it into view.

Scroll snap can be pretty good for that.


Carousels are the modern day <blink> and <marquee> tags. The only difference is that it occasionally has its place with photos, but it's just not optimal for any sort of written content, even if it's just a headline and short description.


nytimes.com uses horizontal carousel on mobile very well, I feel. It's usually for a group of related stories, it's non-intrusive, uses scrolling instead of buttons, and the next story is always partially-visible, which I think is gold-star UI for letting users know it exists.

My understanding is that NY Times spends quite a lot of effort on user metrics, so I would guess, but can't say for sure, that they have evidence that their carousels work.


My clients have large galleries of photos, would you prefer that be paginated?


to a carousel? probably. or infinite scroll, depending on the type of content.

would probably be best to split up the galleries into smaller groupings, though


Yes.


There are plenty of uses for snap scrolling and carousels that aren’t rotating hero images.

See something like https://airbnb.com which uses it for categories a’la the App Store. Image galleries, Netflix-type layouts, etc.


I'm struggling to see how that is different to "rotating hero images". Is it that it doesn't rotate automatically?

What's the UX benefit here?

I get that mobile apps use horizontal swiping and some websites want to be app-like, but even in apps the only common horiztonal-swipe pattern I see is the Android hidden menus pattern, which is (a) a subject of debate in UX circles and (b) absolutely nothing like horizontally scrolling item selection, which is still a bad idea even in native mobile apps.

The other major example I can think of is Instagram's story circles, which I feel must be intentionally unusable to try and force people to view stories in their full-screen tap-to-advance format.


That's a use for sure; though it remains an anti-pattern. Don't mess with the scroll.


> How did I know this would be the top comment on HN?

Actually I was thinking the top comment would be something about the site breaking the back button


I've already commented that today for another post so I'll refrain.


> It seems like the theme of the post is "you don't need JavaScript to do this."

Yet you can't see the examples without JavaScript.


This seems needlessly nitpicky. You need JavaScript to view the embedded CodeSandbox, which is an interactive application within an iFrame. Good luck making what's effectively an IDE without JavaScript.

I suppose the author could show the CSS snippets inline and make you click to a demo, but that's not very fun is it?


You don't need an entire IDE to show examples of content styled with CSS.


The anti-JS mindset (I assume for privacy reasons) seems so backwards to me on a social bookmarking site targeted at programmers/technologists.


We wouldn't have this mindset if sites retained enough basic functionality with it off, which is totally possible. I use NoScript pretty aggressively, and it's astounding how many sites actually render nothing unless you have JS turned on. Browsers and backends both implement form validation, yet most sites today don't support submitting a basic form without JS. I'm not expecting things like Spotify and YouTube to work without JS, but I should be able to at least read most webpages without running full-fledged applications with 7 different tracking scripts and 5 custom fonts.


> If a user wants smooth scroll, they will enable it in their browser.

I really think comments like this aren't helpful and presumptuous to pressing forward. People hate change and love their table layouts... Just going to make a friendly counter argument:

- Did you read what this actually does? It's for anchor tags...

- Bootstrap 5 uses this by default.

- Lot of crappy websites out there. I choose loading one line of CSS versus jQuery + animate all day...

- For perspective, almost 100% of every little interaction on native apps are animated these days. It's liked so much by the general population that, some would say, made iOS so appealing in the beginning to take off. People like interaction.

- It's possible your opinion does not represent the majority anymore (or even that the HN general opinion).

- By making it a browser-defined CSS property versus being JavaScript, you are actually opening accessibility doors for people having this be device configurable.

I really think if someone hates it so much or for accessibility reasons, instead they should just disable it in their browser.

So literally the opposite of what you said.

---

Edit: Example of why this is important to be part of CSS for accessibility versus JavaScript:

```

@media (prefers-reduced-motion: no-preference) {

   :root {
     scroll-behavior: smooth;
   }

 }
```

or:

```

@media (prefers-reduced-motion) {

   .animation { animation: none; }

   :root {
        scroll-behavior: auto;
   }

 }
```

I think HN can chill a bit here.


[flagged]


Wow, quite aggressive.

How is allowing jump-scrolling in response to clicking "ruining scrolling by a dipshit developer?"


Which scroll-related tips are you talking about?

scroll-behavior: smooth seems to only affect the behavior of clicking named anchor tags. It doesn't seem to change the behavior when scrolling with a mouse wheel or trackpad. Other than general accessibility issues related to animations, I don't see any usability concerns here.

scroll-snap-type and scroll-snap-align also don't seem to affect the behavior when scrolling with a mouse wheel or trackpad, except that shortly after you stop scrolling the browser will smoothly scroll to the specified snap points. I suppose this could be over-used (like anything), but it seems to me that there are some pretty obvious places where using this would be entirely appropriate and not unpredictable or disorienting.

::-webkit-scrollbar styling strikes me as the most concerning, both because of how easy and tempting it is to over-use and because the browser support has some subtle gotchas. But this one doesn't seem related to your complaint about smooth versus snappy scrolling.


Yeah, if there's an alternative with functioning scrollbars people will probably use that instead. It's always surprising how popular screwing with basic UI elements like that always becomes.


Good list, I did not know that text image mask effects were so simple. In fact half of these examples covered things I had no idea about.

The custom scrollbars example did not work on Firefox on OSX. all the boxes had identical scrollbars, the OS default.


Firefox only implements the newer standardized scrollbar properties "scrollbar-width" and "scrollbar-color". https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-w...

https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-c...


What a great post, I learned a lot!

I really liked the ones about truncating text - which also taught me what "ellipsis" means. It is the dots in this example:

This text is trun...


One trick that I'm pretty sure I invented is useful in the case where you may be implementing some sort of Material Design palette: you want to use shades of a colour without manually defining them but are losing saturation if you simply use ie. `rgba(255, 255, 255, 0.2)` -- just add `backdrop-filter: saturate(120%)`. This forces the browser renderer to over-saturate the white by mixing in the background colour. Unfortunately Firefox doesn't recognize this CSS property yet but it works fine in WebKit et al.


Interesting, though I would have liked to see the browser support for each of these. Seeing so many -webkit prefixes is a bit concerning.


What is codepen.io? Why does this website need to load from a third party to show text...


Some good tips in there, thanks for sharing.

For anyone looking to really learn CSS for layout the resource I recommend is always https://every-layout.dev

Heydon Pickering and Andy Bell know what they’re talking about, and they explain the “how and why”


I learned some new techniques here! Thanks!


thanks for the typing tip, I once considered using a jquery lib to do the same




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: