CSS recipes

Helpful techniques and snippets for working with my favorite language.

Accordions

Use the <details> element

Borders on images that match the background color

If your website has a white background and you’re displaying images (such as user avatars), it’s likely that some images might have a white or near-white background as well, which can make them hard to distinguish. Using a subtle inset box shadow will create a visible border for these cases that is not really noticeable otherwise like a normal border would be:

box-shadow: inset 0 0 0 1px rgba(0 0 0 / 10%);

Checkboxes

Instead of trying to get the styling right for IE 11, just add custom styles for browsers that support it well. You can do that by checking for support for the -webkit-appearance property:

@supports (-webkit-appearance: none) {
input[type='checkbox'] {
/* style up your checkbox for browsers that can handle it */
}
}

Of course, this idea comes from the great Jen Simmons.

Here’s how to make them simply and accessibly, with no JavaScript, using the :focus-within pseudo selector:

You can also use the <details> element:

Read more about this on the <details> page.

Grid


Horizontal scrolling sections

Thanks to this tweet from Cassie Evans.

.container {
width: 100vw;
display: flex;
flex-wrap: nowrap;
overflow-x: auto;
}

.item {
flex: 0 0 auto;
}

Layout

Responsive tiled layout with CSS Grid and no media queries

This is great for making grid layouts of even-sized tiles where each tile never gets narrower than the specified min-width. But this does not work if you want to have items of varying widths. Stolen from this tweet by @thekitze.

const autoGrid = (minColumnWidth = 250, gap = 0) => css`
display: grid;
grid-template-columns: repeat(auto-fill, minmax(
${minColumnWidth}px, 1fr));
grid-gap:
${gap};
`

Also detailed here by Andy Bell.

This does have a bug though if the user resizes their browser to be less than minColumnWidth. You can fix it using a breakpoint, or using the min CSS function as detailed in this post by Evan Minto, which is beginning to see good browser support.

I wrote a bit about this technique here:

Text dividers

Typography


Misc