Appropriate use of BEM in CSS - css

I'm an old hand with CSS, but have recently decided to take the plunge and begin using BEM. For the most part, I understand the value of using such a flat system, avoiding overly specific selectors etc...
My question is, is the following approach correct. It works, technically, but also seems fragile:
.badge {
/* additional declarations */
background: rgba(0, 0, 0, 0.2);
}
.badge--error {
background: red;
}
.badge--success {
background: green;
}
This works fine, because of the cascading nature of CSS. So the default background is overwritten by the modifier successfully. But if I put the modifier before the initial declaration, the modifier is ignored (because of the equal specificity).
Are there any issues with writing BEM this way? Is it considered bad practice to declare a default value of something like a background within the block, if it's to be overwritten with modifiers? Should the default background in this instance, live in a .badge--default modifier? Or have I written this in a true BEM fashion, and BEM actually relies on CSS' cascading in order to remain flat?

You could make use of CSS variables
.badge {
background: var(--background);
}
.badge--error {
--background: var(--error);
}
.badge--success {
--background: var(--success);
}
:root {
--background: yellow;
--error: red;
--success: green;
}
<div class="badge">
a badge
</div>
<div class="badge badge--success">
a badge success
</div>
<div class="badge badge--error">
a badge error
</div>
<div class="badge" style="--background: purple">
a badge random
</div>
I don't see why a modifier could not modify just a background if it is(n't) set in the initial element.
For BEM I can recommend using a CSS preprocessor like SASS since it make it quite easy to nest elements there is less change of declaring some modifier before the initial declaration. Because of the nesting your CSS becomes much more organised. It is also easier to import different components so each component can live in its own file.
With SASS you can do:
.badge {
&--error {}
&--success {}
}

Related

How do I create a CSS mixin using the new `part` syntax?

I want to apply a number of CSS rules to different selectors, without creating additional selectors. In SCSS, this would be typically done with a mixin, eg:
#mixin gradient-text {
color: transparent;
background-clip: text;
-webkit-background-clip: text;
background-image: linear-gradient(
350deg,
var(--dark-blue),
var(--teal),
var(--bright-green)
);
}
Reading around the internet, there's lots of references to making mixins with the CSS apply syntax, but
https://caniuse.com/sr_css-apply mentions:
#apply was briefly supported behind a flag in Chromium but has since been abandoned in favor of the ::part() selector.
Reading about CSS part though it seems like it's not possible to use CSS part without modifying my HTML and using web components, which have their own issues.
Is it possible to do a mixin in CSS, without modifying my HTML or JS, using part?
According to the MDN article you linked to, ::part can only match elements within a shadow tree. Additionally, the spec for the ::part states
The ::part() pseudo-element only matches anything when the originating element is a shadow host.
Thus, if you wanted to leverage this pseudo-element for CSS mixins, you'd be better working with (developing) a native web component library. You may be able to use the corresponding part HTML attribute outside of the Shadow DOM to implement CSS mixins depending on your requirements.
When in doubt the best thing is to experiment. Here is an example of using ::part() and part (HTML attr) inside and outside of a shadow DOM. Best to test browser support on part as it is a relatively new technology. Moreover, seems there is still ongoing questions about how multiple ident's should be supported, if at all.
customElements.define('custom-thing', class CustomThing extends HTMLElement {
constructor() {
super()
const root = this.attachShadow({ mode: 'closed'})
root.append(document.getElementById('custom').content.cloneNode(true))
}
})
[part~="a"] {
color: red;
}
[part~="b"] {
padding: 20px;
background: gray;
}
p::part(a) {
color: blue !important;
}
custom-thing::part(a) {
color: green;
}
custom-thing::part(a)::after {
content: 'A';
}
custom-thing::part(b) {
color: orange;
}
custom-thing::part(a b) {
/* does multiple ident values work? */
color: blue;
}
<p part="a b">part</p>
<template id="custom">
<style>
p[part="a"] {
color: aqua;
}
</style>
<p part="a">part a</p>
<p part="b">part b</p>
<p part="a b">part a b</p>
</template>
<custom-thing></custom-thing>

CSS variables and custom properties - How do they work?

dynamic-text-colors.css
:root {
--title-color: #555555;
}
.text-title-color {
color: var(--title-color);
}
.bg-blue-100 {
--title-color: #999999;
}
.bg-blue-200 {
--title-color: #888888;
}
.bg-blue-300 {
--title-color: #777777;
}
index.html
<div class="bg-blue-100">
<h1 class="text-title-color">I am colored #999999</h1>
</div>
<div class="bg-blue-200">
<h1 class="text-title-color">I am colored #888888</h1>
</div>
<div class="bg-blue-300">
<h1 class="text-title-color">I am colored #777777</h1>
</div>
Question:
I don't understand the process that allows each h1 to have a different color. In this instance, I don't understand how the value of "text-title-color" can be different based the background color.
"Custom properties are scoped to the element(s) they are declared on, and participate in the cascade: the value of such a custom property is that from the declaration decided by the cascading algorithm." - https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties
According to the explanation above of custom props by Mozilla, each variable is scoped to its element its decalred on. As such, would the browser some how convert the code to something like this and if so where is the code below stored?:
.bg-blue-100 .text-title-color{
color: #999999
}
.bg-blue-200 .text-title-color{
color: #888888
}
.bg-blue-300 .text-title-color{
color: #777777
}
The browser doesn't need to do any conversion in the way you describe
The variables are all part of what it understands.
It's not like a preprocessor which has to convert everything to 'real' CSS before anything runs.
When the browser has to render an h1, say, as in your question it will pick up the value for --title-color from whichever style is relevant. Just as it would pick up, say, the color or width if they were set there.
The value of CSS variables is precisely because they can be set at run time, e.g. by Javascript on some user action and the new value will be used 'on the fly'.

Overriding :root CSS variables from inner scopes [duplicate]

This question already has answers here:
CSS scoped custom property ignored when used to calculate variable in outer scope
(2 answers)
Closed 3 years ago.
In our design system at Stack Overflow, we use Less to compile CSS color values.
We have global Less variables like #orange-500 that are frequently modified for hover states, building border styling, background colors, etc.
In Less, this is written as darken(#orange-500, 5%). I'm trying to achieve something similar using native CSS variables. Switching to CSS variables will allow us to ship features that rely on theming (Stack Exchange Network, Dark Mode, etc.) much faster, with way fewer lines of CSS, while enabling swapping variables on media query (high contrast, dark mode, etc).
This example of overriding our color’s lightness value in hsl works when the variables are scoped to a CSS class:
.card {
--orange: hsl(255, 72%, var(--lightness, 68%));
background: var(--orange);
}
.card:hover {
--lightness: 45%;
}
<div class="card">
Hello world
</div>
However, we need to specify our color variables globally in a single, swappable place to support global theming, but this doesn't work as expected:
:root {
--orange: hsl(255, 72%, var(--lightness, 68%));
}
.card {
background: var(--orange);
}
.card:hover {
--lightness: 45%;
}
<div class="card">
Hello world
</div>
I've tried switching from :root to html or body without any luck. Any workarounds to this?
This is a scoping issue. The way you're doing it, you're inheriting --orange from the :root, and --orange in the :root has a lightness of 68%.
In order to change it, you'll want to re-scope the --orange variable to an element that will look up the new --lightness value. There's a few ways to pull this off:
Option 1: duplicate the --orange variable on the element:
:root {
--lightness: 68%;
--orange: hsl(255, 72%, var(--lightness));
}
.card {
background: var(--orange);
--orange: hsl(255, 72%, var(--lightness));
}
.card:hover {
--lightness: 45%;
}
<div class="card">
Hello world
</div>
Obviously this kinda stinks, because you're going to have to duplicate that --orange variable.
Option 2:
You could abstract the other parameters of --orange so that it's not as duplicative. I'd be a fan of this approach despite the fact that it's more text:
:root {
--lightness: 68%;
--orangeHue: 255;
--orangeSat: 72%;
--orange: hsl(var(--orangeHue), var(--orangeSat), var(--lightness));
}
.card {
background: var(--orange);
--orange: hsl(var(--orangeHue), var(--orangeSat), var(--lightness));
}
.card:hover {
--lightness: 45%;
}
<div class="card">
Hello world
</div>
What you could also do is scope this specifically to a .darkMode class that might be applied to the HTML element or the body. This could also make sense because it's clear what the intent is from the code:
Option 3
:root {
--lightness: 68%;
--orangeHue: 255;
--orangeSat: 72%;
--orange: hsl(var(--orangeHue), var(--orangeSat), var(--lightness));
}
.card {
background: var(--orange);
}
.card:hover {
--lightness: 45%;
}
.darkMode .card {
--orange: hsl(var(--orangeHue), var(--orangeSat), var(--lightness));
}
<div class="darkMode">
<div class="card">
Hello world
</div>
</div>
Regardless of how you go, the issue is that the --orange variable is inheriting from its original scope where --lightness is set. Think of it as "inheriting a computed value".
In order to get --orange to get the new lightness, you need a new --orange somewhere.
Option 4
I'm not sure what your theme pattern is, but I can explain how I created a dark mode on my own blog . If you look at the CSS What you'll see is that I've created two complete themes that follow the same naming convention:
--themeLightTextColor: rgb(55, 55, 55);
--themeLightBGColor: rgb(255, 255, 255);
--themeLightAccentColor: rgb(248, 248, 248);
--themeLightTrimColor: rgb(238, 238, 238);
--themeDarkTextColor: rgb(220, 220, 220);
--themeDarkBGColor: rgb(23, 23, 23);
--themeDarkAccentColor: rgb(55, 55, 55);
--themeDarkTrimColor: rgb(40, 40, 40);
What I then do is create a third set of variables whose job it is to be the "active" managers:
--themeActiveLinkColor: var(--linkColor);
--themeActiveLinkColorHover: var(--linkColorHover);
--themeActiveTextColor: var(--themeLightTextColor);
--themeActiveEditorialTextColor: var(--themeLightPltNLow);
--themeActiveBGColor: var(--themeLightBGColor);
--themeActiveAccentColor: var(--themeLightAccentColor);
--themeActiveTrimColor: var(--themeLightTrimColor);
Then, I scope the active theme settings under a single class:
.theme--dark {
--themeActiveTextColor: var(--themeDarkTextColor);
--themeActiveEditorialTextColor: var(--themeDarkPltNLow);
--themeActiveBGColor: var(--themeDarkBGColor);
--themeActiveAccentColor: var(--themeDarkAccentColor);
--themeActiveTrimColor: var(--themeDarkTrimColor);
}
It seems like maybe your intent is to not have to explicitly declare a theme, but rather tweak some "root variables" to adjust it. But I would suggest that maybe you have a pattern in place where a single class can change an active theme. The advantage to this pattern is that you would be able to also adjust any "root variables" on the class name.
I would be interested to learn if there is anything more ideal than this solution but as a possible workaround, you can break up your CSS variables a bit further and build the values inside the element style definitions like so:
:root {
--orangeColor: 37,72%;
--redColor: 1,72%;
--blueColor: 215,72%;
--greenColor: 126,72%;
--LumDefault: 68%;
--LumDark: 45%;
--LumLight: 80%;
}
.card {
background: hsl(var(--orangeColor), var(--LumDefault));
}
.card:hover {
background: hsl(var(--orangeColor), var(--LumDark));
}
.card:active {
background: hsl(var(--redColor), var(--LumDark));
color: hsl(var(--greenColor), var(--LumLight));
}
<div class="card">
Hello world
</div>
I do realize that this does not override as you wanted to accomplish but from the business case you stated, it will give you a way to manage elements at a global level...just a bit more work in defining your CSS on the front end.
The simple solution is to place the CSS variables into a separate CSS file and then swap it out as needed. For example, a media query to support dark mode could do the swap or you could use JavaScript, a pre-baked theme, etc.
What's nice about this is swapping the CSS file with your variable definitions changes the CSS rendering in real-time.
Assume you're using media queries for light/dark mode. If the browser understands and requests "dark mode" then only the first file is loaded. However, if the browser doesn't understand those media queries your "default" is the light.css since both CSS files are loaded but subsequent rules override previous rules.
<link rel="stylesheet" href="/dark.css" media="(prefers-color-scheme: dark)">
<link rel="stylesheet" href="/light.css" media="(prefers-color-scheme: no-preference), (prefers-color-scheme: light)">
<!-- The main stylesheet -->
<link rel="stylesheet" href="/style.css">
Inside those stylesheets, you want to use the :root pseudo-class as it's basically the same as HTML, but has higher specificity in most browsers.
light.css
:root {
--text-color: #333;
--background-color: #fff;
}
dark.css
:root {
--text-color: #dadada;
--background-color: #333;
}
Also, note that simplifying the variables and building the full rule inside the element is a good idea as Travis mentions in that answer.
style.css (main styling document)
body {
color: var(--text-color);
background-color: var(--background-color);
}
As a side note, you may want to read up on the CSS color-scheme property to get a bit better support with native browser elements.

How to avoid css selector applying style rules from another file

I came across this problem while handling a large project and felt that i should seek an opinion from the community here.
I have specified a css class 'header' in style1.css, i.e.
.header { color: red;}
In another file, I inadvertently, named a class 'header' again with this rule :
.header { background-color: yellow; }
When i refreshed the browser i noticed the red font and after examining the style inspector found the problem. I tried to avoid the problem by applying specificity, i.e. #some-div .header, but that didnt stop it from applying the red font. Of course i could simply solve the problem by renaming header to something else, but i'm curious how developers who handle large projects handle this. Thanks for your time.
Well, from your code, you specified values for different properties in the two declarations of the header class. The first declaration specifies a color property and the second specifies a background-color property. From all indications you're not really "overriding" anything since you didn't give conflicting values for one property so, CSS is simply giving the values of the first declaration of the header class to the second one because there's no difference. If you wanted to override it for the second you'd have to probably add a different identifier to the second declaration of the header class to point to a unique element and specify a different value for the color property. Hope this satisfied your curiosity.
Just add a different class to one of the cases. For example:
.header {
color: red;
}
.header.yellow-bg {
color: initial;
background-color: yellow;
}
<h3 class="header">Red header</h3>
<h3 class="header yellow-bg">Black/yellow header</h3>
The second declaration for color applies because it is more specific (2 classes > 1 class).
Don't use !important as another user suggested. Avoid it all costs. It's the easy way out for the moment, but once you start going down that road, you're going to end up with a stylesheet that's terrible to manage.
Set your styles for a specific base and use classes and more specific selectors as overrides. Remember that stylesheets cascade.
For example, say you have a typical header font color that should be your .header. If you have other one-off or unique headers that share same structure provide another class to that which makes sense to you.
So as an example:
Both headers have the .header styles but headers with the special class have blue text color which overrides red.
.header {
color: red;
width: 100%;
display: block;
background-color: #eee;
padding: 10px;
margin: 2px;
}
.header.special {
color: blue;
}
<div class="header">Regular Header</div>
<div class="special header">Special Header</div>

Can I include a css definition in another css definition?

So let's say I have the following in 'foo.css':
.border { border : solid 1px; }
#foo { color : #123; }
#bar { color : #a00; }
Now let's say that I have two divs I want borders for, so I do:
<div id="foo" class="border">Foo</div>
<div id="bar" class="border">Bar</div>
This works fine, but I find that when defining #foo and #bar in my css file, I would rather give them the characteristics of .border than give the div's the class, like so:
.border { border : solid 1px; }
#foo {
<incantation to inherit from .border>
color : #123;
}
#bar {
<incantation to inherit from .border>
color : #a00;
}
and then my html would just be:
<div id="foo">Foo</div>
<div id="bar">Bar</div>
Anybody know what that magic incantation is?
That is not supported by css. The best you can do is something like:
#foo, #bar, .border { border : solid 1px; }
#foo { color : #123; }
#bar { color : #a00; }
You might be interested in mixins with Sass. Sass lets you write css style sheets in a more efficient way, using tricks like this. Mixins let you define a group of attributes (say, to do with borders), and then include those attributes within certain css classes.
As Wsanville said, you can't use the class.
But normal CSS inheritance does work - say if your html was
<div class="border">
<div id="foo">
hello
</div>
<div id="bar">
world
</div>
</div>
You could say
.border {border: 1px solid #f00;}
#foo {border:inherit;}
Which in some cases might be good enough
If you're looking to push your CSS further instead of using some of the tricks outlined in earlier posts, you should look into CSS Compilers. They take CSS-like code you've writen, usually CSS with a few tricks added in, and turn them into normal CSS for the web.
David Ziegler wrote about some of the cool featured CSS compilers offer:
Variables - Good programmers don’t like to hardcode. In many cases you can avoid this in CSS by using good inheritence, but sometimes it’s unavoidable. With variables, changing your color scheme means updating one variable instead of 13 attributes.
Math - This goes hand in hand with variables. Say your left column is 100px, your right column is 500px, and your wrapper div is 600px. Well, maybe you decide to change it to 960px. Wouldn’t it be awesome if the width of your columns adjusted automatically? The answer is yes.
Nested Styles - This is probably the most important. CSS is flat, which means complex sites end up with CSS that is a pain to go through.
You can read about popular compilers in his blog post on the subject, or do some searching and find one that works best for you.

Resources