13,90 €
14,90 €
11,50 €19,90 €
11,50 €19,90 €
13,99 €19,90 €
14,99 €20,90 €
11,50 €17,90 €
20,00 €
18,90 €
18,00 €23,90 €
Something I’ve been wanting for a long time, define different regions like a footer section, or side bar and not have to deal with all the contextual styling hassle. A.k.a. “Now that this button is used on a dark background, the button needs to change its colors too. Where should the styles live?”. Here an old post about struggling with contextual styling.
So then the other day I was doing some experiments with using custom properties for Atom’s UI. Turns out, using custom properties might make contextual styling a bit easier. For the rest of the post, let’s switch to a more simple example. A page where the main area is light, but then has a dark hero and footer section. Like this:
In the past, I probably would’ve created variations like Button--dark
or overwrote it with header .Button {…}
. Depends a bit on the project. Here another approach: Create themes with a set of variables, then apply the theme to the different areas.
First let’s define our default theme with a bunch of variables.
[data-theme="default"] {
--fg: hsl(0,0%,25%);
--border: hsl(0,0%,75%);
--bg: hsl(0,0%,95%);
--button-bg: hsl(0,0%,99%);
--input-bg: hsl(0,0%,90%);
}
Then we create some components where we use the variables defined above.
[data-theme] {
color: var(--fg);
background-color: var(--bg);
}
.Button {
color: var(--fg);
border: 1px solid var(--border);
background-color: var(--button-bg);
}
.Input {
color: var(--fg);
border: 1px solid var(--border);
background-color: var(--input-bg);
}
And lastly we add the [data-theme="default"]
attribute on the body so that our components will pick up the variables.
<body data-theme="default">
If you wonder why use data-theme
attributes over classes? Well, no specific reason. Maybe with attributes, it’s a hint that only one theme should be used per element and is more separated from your other classes.
At this point we get this:
See the Pen Contextual styling with custom properties (1/3) by simurai (@simurai) on CodePen.
But our designer wants the hero and footer to be dark. Alright, let’s define another theme region.
[data-theme="dark"] {
--fg: hsl(0,10%,70%);
--border: hsl(0,10%,10%);
--bg: hsl(0,0%,20%);
--button-bg: hsl(0,0%,25%);
--input-bg: hsl(0,0%,15%);
}
And add the theme attribute to the header and footer.
<header data-theme="dark">
<footer data-theme="dark">
Which gives us this:
See the Pen Contextual styling with custom properties (2/3) by simurai (@simurai) on CodePen.
The reason why this works is that custom properties cascade and can be overridden on nested elements, just like normal properties.
A few months pass and our designer comes back with a redesigned hero section. “To make it look fresh” with a splash of color.
No problem! Just like with the dark theme, we define a new “hero” theme.
[data-theme="hero"] {
--fg: hsl(240,50%,90%);
--border: hsl(240,50%,10%);
--bg: hsl(240,33%,30%);
--button-bg: hsl(240,33%,40%);
--input-bg: hsl(240,33%,20%);
}
<header data-theme="hero">
And here is that fresh hero:
See the Pen Contextual styling with custom properties (3/3) by simurai (@simurai) on CodePen.
It’s also not limited to colors only, could be used for sizes, fonts or anything that makes sense to define as variables.
Using these theme “regions” lets your components stay context un-aware and you can use them in multiple themes. Even on the same page.
Less time to talk about who, how and where, more time to talk about the weather. ☔️????
Yeah, right. The big question: But does it scale? Can this be used for all use cases.
Ok, I’m pretty sure it doesn’t fit all situations. There are just too many to find a single solution for them all. And I’m actually not sure how well it scales. I guess it works great in these simple demos, but I have yet to find a larger project to test it on. So if you have used (or plan to use) this approach, I’m curious to know how it went.
A concern I can imagine is that the list of variables might grow quickly if themes have totally different characteristics. Like not just a bit darker or lighter backgrounds. Then you might need to have foreground and border colors for each component (or group of components) and can’t just use the general --fg
and --border
variables. Naming these variables is probably the hardest part.
@giuseppegurgone made an interesting comment:
in suitcss projects I used to define component level custom props, theme variables and then create themes by mapping the former to the latter suitcss-toolkit
So if I understood it correctly, by mapping theme variables to component variables, you could avoid your theme variables from growing too much and you can decide for each component how to use these theme variables.
If it’s too early to use custom properties in your project, @szalonna posted an example how to do something similar in SCSS.
Double-hue syntax themes for Atom.
DuoTone themes use only 2 hues (7 shades in total). It tones down less important parts (like punctuation and brackets) and highlights only the important ones. This leads to a more calm color scheme, but still lets you find the stuff you’re looking for.
A big thanks goes to @braver who did most of the initial language support.
And here some more color variations created by other theme authors.
The cascade in CSS is a curse and blessing at the same time. It usually works quite well, but there are issues that let people get all worked up and ask the question Do We Even Need CSS Anymore. I can somewhat relate to that - but I also think it’s not the cascade alone and also about fighting specificity. Not running into issues with specificity is hard. Almost as hard as pronouncing that word.
In this post I’ll try to show a few ways how you can make the cascade be your friend and maybe reduce the need of overriding and thus encounter less fighting with specificity.
For every CSS property that you write, try to move it up the tree as far as possible. In other words: Back to the :root.
For example, our site has a side bar and we want to add a short bio to it. The markup might look something like this:
<body>
<main class=“Posts”>
<aside class=“SideBar”>
<nav class=“Nav”>
<p class=“Bio”>
And the CSS:
.Bio {
font-size: .8em;
line-height: 1.5;
color: #888;
}
That would work. But if we look at the Nav that is already in the SideBar, chances are good that some of the styles are the same. In our case it’s font-size
and color
. So let’s remove those properties from Nav and Bio and add it to the shared parent element, the SideBar.
.SideBar {
font-size: .8em;
color: #888;
}
And as it turns out, that line-height: 1.5;
is already defined for our Posts. So since it seems that the whole page uses the same line-height, let’s remove it from the Bio and Post elements and move it all up to the root node.
:root {
line-height: 1.5;
}
This probably sounds like common sense, but often it’s tempting to just style your new thing without even looking if some of the sibling elements define the same thing. This also happens when you copy&paste styles from another section or when pasting some snippets you found online. It might take a bit more time to refactor and seems scary, but it should keep our CSS in a healthier state.
Style the branches, not each leaf
Style certain properties always as a combo.
A good example is the color
and background-color
combo. Unless you make only small tweaks, it’s probably a good idea to always change them together. When adding a background color to an element, it might not contain any text, but probably some child will. Therefore if we set foreground and background color together, we can always be sure we won’t run into any legibility and contrast issues. Also, next time we change a background color, we don’t have to hunt for all the text colors that need to be changed too, it’s right there in the same place.
Screenshot from Colorable
Use “dynamic” values, such as
currentColor
andem
s.
Sometimes it might make sense to use the text color
for other properties. Like for border
, box-shadow
or for the fill
of SVG icons. Instead of defining them directly you can use currentColor
and it will be the same the color
property. And since color
inherits by default, you might can change it in only one place.
Similarly em
s are mapped to font-size
allowing you to scale everything by just changing the :root font size.
Here a few more details on currentColor and EMs.
Override UA Styles to
inherit
from its parents.
Form controls like buttons, inputs get styled by the browser in a certain way. Overriding them with inherit
makes them adapt to your own styles.
button,
input,
select,
textarea {
color: inherit;
font-family: inherit;
font-style: inherit;
font-weight: inherit;
}
The example above is taken from sanitize.css. normalize.css does the same, so if you use them, you’re already covered.
You can also try to restyle other inputs like a range slider, radio, checkbox etc. And as seen above, by using currentColor
, make them automatically match the color property. And maybe move them from a light into a dark theme without changing anything.
That’s all nice stuff, but who is it for? Well, of course it can’t be forced upon every situation. I would say small and simple web sites benefit the most. But even when using a preprocessor, it might not hurt if it reduces the amount of CSS that gets output or when a few variables aren’t even needed.
Also it seems suited for the “single purpose class” approach like Tachyons. It might reduce complexity and the amount of classes that are needed.
Another interesting thing could be the upcoming custom properties a.k.a. CSS variables. Unlike variables in preprocessors, when overriding a custom property, it will only affect the current selector scope. So in a sense they will be “cascading variables”. But I still have to try that out and see how it works in practice.
ps. It is possible that this post is inspired by this tweet.
Using CSS components is somewhat straightforward. We add the markup and give it the component’s class name and all is good. Where it gets trickier is when we try to nest components. And when they need to be tweaked based on the context. Where should the styles be defined? It’s a question I’ve been asking myself a few times and what this article is trying to explore.
Just to clarify before we start, with “CSS components”, I mean the small building blocks that get used to assemble a website or app. Like buttons, inputs, navs, headers etc. Some also call them modules or patterns. Also I’m using the SUIT naming convention in the examples below, but any other convention would be fine as well. And just a heads, there isn’t some awesome solution at the end that solves all the problems. It’s just me whining most of the time.
Ok, best is to go straight into it and look at an example. Let’s say we have a Header component where we would like to add a Button component inside.
<header class=“Header”>
<button class=“Button”>Button</button>
</header>
Now because the Button is inside the Header, we want to make the Button a bit smaller than it would be on its own.
Here a few approaches how to do that:
Maybe the most common way is to use a descendant selector to change the font-size
whenever a Button is inside a Header.
.Header .Button {
font-size: .75em;
}
This works great but the question is, where should this rule be added? We probably split our components into separate files, so is it in header.scss
or in button.scss
? In other words, should the Header know about what other components might get nested or should the Button know in what environment it will get placed?
But wait, the point of creating components is to separate them, make them modular. Each component should be kept isolated and shouldn’t know about other components. So we can make changes, rename or remove them without having to check if they might get used somewhere else.
Another way is to create variations. We add a .Button--small
class that we can use whenever we would like the button to be smaller without having to worry about ancestors.
.Button--small {
font-size: .75em;
}
<header class=“Header”>
<button class=“Button Button--small”>Button</button>
</header>
This works great too, but could get out of hand quickly. What do you do if at some point you want the font-size
to be .9em
? Create yet another variation? Button--justALittleSmaller
. As the project keeps growing, the number of variations will too. We will start to loose sight where they actually get used and we’re not sure anymore if we can change a variation or if it will have side effects in some other place. We could create “contextual” variations like Button--header
or Button--footer
, but then we’re back at the beginning and could just as well use “descendant selectors”.
Same goes for using states. .Button.is-small
should only be used if there is a change in state and not to fit a certain context.
I can’t remember where I read about this approach but somehow it stuck with me. I also forgot how it was called. So for now I’ll just call it “Adopted Child”.
Let’s switch it around and look at it from the Header’s perspective. What would we do if we wouldn’t know what the components are called that might get nested? But we know that we want to make them a bit smaller. Well, we probably would create a generic .Header-item
class and use it like this:
.Header-item {
font-size: .75em;
}
<header class=“Header”>
<div class=“Header-item”></div>
</header>
Ok, that gets us a bit closer. Now, it’s probably strange saying it like that when talking about CSS, but what would we do if we don’t want to create an own child, but still have one. Right, we could adopt one. In our example we adopt a Button component as our own child. We didn’t create it, but now we can tweak.. erm.. I mean “raise” it like it’s our own:
// born in button.scss
.Button {
font-size: 1em;
}
// raised in header.css
.Header .Header-item {
font-size: .75em;
}
<header class=“Header”>
<button class=“Header-item Button”>Button</button>
</header>
It is a bit uncommon that the same HTML element shares classes from two different components. And it’s not without any risks. More about them later. But I really like this approach because it keeps the components independent without having to know about each other.
Another nice thing is that if we want to add other components to the Header that also need the same adjustments, we can reuse the same Header-item
class, like for example on a text Input.
<header class=“Header”>
<input class=“Header-item Input”>
<button class=“Header-item Button”>Button</button>
</header>
Ok, about those risks. Well, depending on what properties we wanna change, it might not always be ideal. For example, because the Button already had font-size
defined, we had to increase specificity by using .Header .Header-item
. But that would also override variations like .Button--small
. That might be how we want it, but there are also situations where we’d like the variation to always be “stronger”. An example would be when changing colors. When the color of Buttons should be different inside a Header, but not when its a variation, like .Button—primary
. Yeah, we could take a look inside button.scss or our style-guide, but remember our goal.. we actually don’t want to make decisions by looking how other components are made.
So, as a general rule, don’t use “adopted children” for any properties that are theme related and only where you can be sure that you want to override them all the time. Like for layout/size related properties or adjusting the position.
There are some more ways to do contextual styling that came to mind. I’ll just mention them briefly for completeness, but think the 3 above are better suited.
Option 4 - We could use a preprocessor to extend an existing component. In our example it would be a clone of the Button with some tweaks added and used as a new child component .Header-button
. Now we only rely that the Button exists in the source, but don’t have to worry about other contexts. Downside is inflating our CSS output. As well as having to remember lots of new child component classes.
Option 5 - We could create a utility class like .u-small
. It’s similar to variations, but not scoped to a single component and could be used for other components as well. And for that reason it becomes very risky to ever change later.
Option 6 - And of course, we could use inline styles. But I would leave that to JavaScript only.
So after all that, which is best? I’m afraid there isn’t a clear winner. It would be nice to keep it consistent with a single approach throughout the entire project, but I guess we just have to decide on a per case basis:
As said at the beginning, I haven’t found a “fits all” solution and maybe the conclusion is: Try to keep contextual styling to a minimum.
The “Adopted Child” approach is called “Mixes” in BEM. Here some more infos.
SUIT also recommends using “Adopted Child/Mixes”. But also another option:
Option 7 - Adding a wrapper element. It’s the <div class="Excerpt-wrapButton">
in that example. I think it works great in most cases. But for example when using Flexbox, because it has this parent/child relationship, adding an extra wrapper in between would break it. And then you might still need to set the width of the wrapped component to 100% or so. Anyways, this is a great addition. Thanks Pablo in the comments.
Option 8 - Single Purpose Classes. It’s where every class has only a single property. It’s somewhere between utilities (Option 5) and inline styles (Option 6). Atomic CSS and Tachyons use this approach. I haven’t used them on a real project, but just from looking at it, the concerns are similar to the ones from utilities. If you want to change the value in a SP class, it seems unpredictable. Because in another place (where that same class is used), you might want to keep the current value. So you would have to first check if the change has any unwanted effects somewhere else.
This is my (living) collection of front-end links. It’s not complete by all means, in fact, there isn’t any of the obvious ones, like Can I use or so. Just some links that I need occasionally but can’t remember their names, so I saved them here for quick access. Also, they’re somewhat randomly ordered.
Note to self: Edit source
A lot of photo apps allow you to add filters before sharing. The typical UI for picking a filter is a row of little thumbnails that can be horizontally scrolled. I’m sure you’ve used it many times. It looks something like this:
A filter picker like that is easy to understand and works pretty well. But in my case, there is something that has been bugging me a bit. Here is how I use it:
Now, I don’t really know how most people use these filter pickers. Could be that:
So I was thinking about some possible improvements:
Automatically order the filters based on how often they get used. This makes filters that you use most appear at the beginning and are easier to get to. You could always keep scrolling in case you’re in the mood for something new. This would of course mess it up for people that have filters remembered by position. But not sure how many actually do that.
Let people manually reorder the position. Could be done similar like the home screen icons on iOS (long press until they wiggle, then drag around). I would probably move my favorites to the front and also sort based on color/style.
Let people temporarily toss away the filters they don’t want. This would allow you to narrow down your selection to just a few for easier comparison. Of course, all the filters would be back next time you take a new photo.
Or probably even better (3B): Instead of throwing away the ones you don’t like (could be tedious if there are a lot of filters), you could push up only the ones you like and they would move to the right with a visual separator. It’s similar how you can pin a Chrome browser tab to separate it from the rest. Then once you scrolled to the end, you would have all your previously selected filters next to each other, waiting to be the lucky winner.
I understand that the suggestions might make a photo app more complicated and harder to explain to a new user. But it could be more a “power user” feature that you’re not forced to use if you don’t want to. Anyways, in case I’m not the only one with this (small) problem, I hope some day we will have a better way to filter filters. Ohh.. and let me know if you’re already using an app that tackles this somehow.
Thanks for all the comments. Good to see more people thinking about this. I played around a bit more with the demo, mostly after the conversation with Ignacio in the comments below. So here a 4th option:
Let people select a couple filters and then cycle through them by tapping on the photo. It’s actually similar to 3B, but it keeps the UI simple by using the photo as the secondary navigation control. Here the steps how to use:
Try the demo.
The implementation of the demo could still be improved. It is a bit hard to discover that you can tap the photo to cycle through your favorites. Might need some visual clue to help understand it better. Adding swipe gestures instead of tapping would also improve UX. Or to remove a filter from your favorite selection, you could just swipe down on the image. Also note that the filters are CSS based and still a bit glitchy when animating. But you should get the idea.
Manuel Haring explored a similar concept where you can push up filters to narrow down your selection.
Here a larger video that has even a third selection stage.
So let’s say we have a “bar” with some items inside. Like a header or footer. Let’s also say we want those items to be spaced evenly, meaning they have the same gap everywhere. Shouldn’t be a big problem. Let’s take a look:
We can’t just add margin: 2rem
to the elements since there is no margin collapsing on the horizontal axis. And it also doesn’t work when using Flexbox. Leaving a double sized gap in between. Wishing there is something like margin: 2rem collapse;
where you can enable/disable it optionally.
See the Pen Spacing elements (no collapsing) by simurai (@simurai) on CodePen.
Using margin: 2rem 0 2rem 2rem
and then a pseudo class like :last-child { margin-right: 2rem }
to add the extra margin works as long as you don’t need to hide that element with display: none
. Maybe a rare case, but I’ve been running into this issue once in a while. Would be cool if there is something like :last-displayed
that would ignore elements that have display:none.
See the Pen Spacing elements (pseudo) by simurai (@simurai) on CodePen.
The easiest way I think, is to add margins to all elements (like in the first example), but then also add the same value as padding
to the parent element. Like this:
.Header {
padding: 1rem;
}
.Header-item {
margin: 1rem;
}
That way all elements are evenly spaced and you still can use display:none
without having to worry about breaking it. A little flaw is that you have to keep the 2 values in sync, but if you’re using a preprocessor, it can just be a single variable. Or maybe you could use REM’s to control it with font-size
from the :root.
See the Pen Spacing elements by simurai (@simurai) on CodePen.
There are more ways but I’m not aware of a simple one that also let’s you use display: none
. Let me know otherwise.
A couple more options:
Hmmm.. gotta try some. I kinda like the 3rd one. Keeps it independent from the parent and is not “too” complicated.
At this year’s CSSConf in Melbourne (AU) I gave a talk called “Styling with STRINGS”. The talk is about how we can use Flexbox, currentColor and __EM__s inside components to quickly style entire Web Apps straight in the browser.
In case of tl:dw here some of the main points:
When creating mobile “App” layouts, where not the whole page is scrollable, but instead only certain parts. And you have anchored areas like header/footer and a main area that should fill out the available space, then the easiest way is to use Flexbox.
This lets you easily drag around components that are set as flex items and they always position nicely. Using flex: 1;
on components makes them stretch out and fill the available space. A good use case is a search input or a title.
If you don’t specify the border-color
(initial value) it will be the same value as color
.
Furthermore there is a color value called currentColor
. As the name indicates, it’s also mapped to the current color value. We can use it as background-color
for example. Not that useful when the text should be readable, since now text and background are the same color, but for some components without text it can be quite useful. Like in the example below with the slider thumb.
If a component set should look similar to the “iOS 7” style then currentColor works great. Below all components have no color values at all and only use currentColor. This let’s us change everything by only changing the color value in the root html element.
In a similar way, EM
s are mapped to font-size
. So if we use EMs to define only the proportions of a component, we can use font-size to scale it up/down. And if we inherit
the font-size we could also control everything at once with just a single property in the root or in groups if we go deeper down the DOM tree.
REM
s work the same except that they are tied to the root html element only. We could use it to control the spacing of the components by using REMs for margin/padding.
I wrote about this in more detail in the Sizing (Web) Components post.
Now if we combine this all and test it in an example application, we can easily design many variations right from the DevTools/inspector in a quick and easy way.
Feel free to play around with the CSSConf App yourself or check out the source on GitHub.
You might wonder how you can save the changes made in the DevTools/inspector without having to manually copy them over into your CSS file. In Chrome there is a feature called Workspaces. It let’s you map a URL to a local folder. Once that is setup, all CSS changes will automatically be saved to your local disc. Here a post that explains how to setup Workspaces. It’s advised to use version control like Git, so that you can always discard all changes if you went too far and wanna start over.
Admittedly it is somewhat in between of being useful for production and just a “hack”. Especially the currentColor
. But the main point of the talk is best told by this quote:
“Creators need an immediate connection” — Bret Victor
The examples I used are just the closest I could get using CSS alone and still keep code clean. I hope we keep that principle alive and improve on it.
ps. Artist of the puppet master illustration: Unknown.
pss. Here all the other videos from CSSConf.
I haven’t redesigned my site for years, can’t even remember exactly. Also, haven’t been posting for a while. So as a New Year’s resolution I redid my site using Jekyll and am hosting it as a GitHub page.
At some point, while working on the MontageJS framework, the question came up what CSS naming convention we should start using. After a long discussion we settled on using the BEM methodology, but changed the syntax a bit. To keep this post short, I won’t go into detail why using BEM is a good idea, but rather explain why we chose a different syntax. Here some examples:
.digit-Progress /* org-Component */
.digit-Progress-bar /* org-Component-childElement */
.digit-Progress--small /* org-Component--variation */
Note: The
org-
(digit-) prefix is used as a name-space so it wouldn’t conflict with other packages/libraries/frameworks.
Now let’s take a look at the reasons for choosing such a syntax.
The main reason why we’re using a hyphen (-
) instead of underscores (_
), has to do with the fact that their behavior is different when double-clicking to select text. Try for yourself:
component__element /* underscores */
component-element /* hyphen */
See how when you’re using underscores it selects the part before and after, in this case the whole component__element
. But with hyphens it let’s you select only the part you double-clicked. component
OR element
. This let’s you quickly edit only the parts you want:
Now, what if the component or child element consists of multiple words? We could use underscores like component_name-element_name
. It would still be double-clickable, but readability suffers since it’s harder to see what belongs together. Better to use camelCase which groups each part visually: componentName-elementName
.
OK, I think we’re getting closer. As a last rule, for the “main” component we use PascalCase
. The reason for it is to add emphasis and make it easier to distinguish the main component from a child element. Also when using a namespace, the component moves to the second position, which makes it even more important to have it stick out: org-Component-childElement
We kept the more commonly used double hyphens (–) for variations. digit-Progress--small
. It makes sense, because it pulls the variation (–small) visually more apart and makes it look like it’s something “different” than the default component.
So that’s about it. For more details about this naming convention, take a look at the SUIT framework, which also started to use the same syntax and documented it really well.
In the end, whatever Shade of BEM you choose to cook with probably depends on your personal taste, but thinking about a great UX by improving usability and readability won’t hurt either.