CSS is designed in a way that allows for relatively seamless addition of new features. Since the dawn of the language, specifications have required browsers to gracefully ignore any properties, values, selectors, or at-rules they do not support. Consequently, in most cases, it is possible to successfully use a newer technology without causing any issues in older browsers.
Consider the relatively new caret-color property (it changes the color of the cursor in inputs). Its support is still low but that does not mean that we should not use it today.
.myInput {
color: blue;
caret-color: red;
}
Notice how we put it right next to color, a property with practically universal browser support; one that will be applied everywhere. In this case, we have not explicitly discriminated between modern and older browsers. Instead, we just rely on the older ones ignoring features they do not support.
It turns out that this pattern is powerful enough in the vast majority of situations.
When feature detection is necessary
In some cases, however, we would really like to use a modern property or property value whose use differs significantly from its fallback. In those cases, @supports comes to the rescue.
@supports is a special at-rule that allows us to conditionally apply any styles in browsers that support a particular property and its value.
@supports (display: grid) {
/* Styles for browsers that support grid layout... */
}
It works analogously to @media queries, which also only apply styles conditionally when a certain predicate is met.
To illustrate the use of @supports, consider the following example: we would like to display a user-uploaded avatar in a nice circle but we cannot guarantee that the actual file will be of square dimensions. For that, the object-fit property would be immensely helpful; however, it is not supported by Internet Explorer (IE). What do we do then?
As a not-so-pretty fallback, we will squeeze the image width within the avatar at the cost that wider files will not completely cover the avatar area. Instead, our single-color background will appear underneath.
Even though the Selectors Level 4 specification is still a Working Draft, some of the selectors it defines — such as :placeholder-shown — are already supported by many browsers. Should this trend continue (and should the draft retain most of its current proposals), this level of the specification will introduce more new selectors than any of its predecessors. In the meantime, and also while IE is still alive, CSS developers will have to target a yet more diverse and volatile spectrum of browsers with nascent support for these selectors.
It will be very useful to perform feature detection on selectors. Unfortunately, @supports is only designed for testing support of properties and their values, and even the newest draft of its specification does not appear to change that. Ever since its inception, it has, however, defined a special production rule in its grammar whose sole purpose is to provide room for potential backwards-compatible extensions, and thus it is perfectly feasible for a future version to add the ability to condition on support for particular selectors. Nevertheless, that eventuality remains entirely hypothetical.
Selector counterpart to @supports
First of all, it is important to emphasize that, analogous to the aforementioned caret-color example where @supports is probably not necessary, many selectors do not need to be explicitly tested for either. For instance, we might simply try to match ::selection and not worry about browsers that do not support it since it will not be the end of the world if the selection appearance remains the browser default.
Nevertheless, there are cases where explicit feature detection for selectors would be highly desirable. In the rest of this article, we will introduce a pattern for addressing such needs and subsequently use it with :placeholder-shown to build a CSS-only alternative to the Material Design text field with a floating label.
Fundamental property groups of selectors
In order to avoid duplication, it is possible to condense several identical declarations into one comma-separated list of selectors, which is referred to as group of selectors.
Thus we can turn:
.foo { color: red }
.bar { color: red }
…into:
.foo, .bar { color: red }
However, as the Selectors Level 3 specification warns, these are only equivalent because all of the selectors involved are valid. As per the specification, if any of the selectors in the group is invalid, the entire group is ignored. Consequently, the selectors:
..foo { color: red } /* Note the extra dot */
.bar { color: red }
…could not be safely grouped, as the former selector is invalid. If we grouped them, we would cause the browser to ignore the declaration for the latter as well.
It is worth pointing out that, as far as a browser is concerned, there is no difference between an invalid selector and a selector that is only valid as per a newer version of the specification, or one that the browser does not know. To the browser, both are simply invalid.
We can take advantage of this property to test for support of a particular selector. All we need is a selector that we can guarantee matches nothing. In our examples, we will use :not(*).
.foo { color: red }
:not(*):placeholder-shown,
.foo {
color: green
}
Let us break down what is happening here. An older browser will successfully apply the first rule, but when processing the the rest, it will find the first selector in the group invalid since it does not know :placeholder-shown, and thus it will ignore the entire selector group. Consequently, all elements matching .foo will remain red. In contrast, while a newer browser will likely roll its robot eyes upon encountering :not(*) (which never matches anything) it will not discard the entire selector group. Instead, it will override the previous rule, and thus all elements matching .foo will be green.
Notice the similarity to @supports (or any @media query, for that matter) in terms of how it is used. We first specify the fallback and then override it for browsers that satisfy a predicate, which in this case is the support for a particular selector — albeit written in a somewhat convoluted fashion.
We can use this technique for our input with a floating label to separate browsers that do from those that do not support :placeholder-shown, a pseudo-class that is absolutely vital to this example. For the sake of relative simplicity, in spite of best UI practices, we will choose our fallback to be only the actual placeholder.
As before, the key is to first add styles for older browsers. We hide the label and set the color of the placeholder.
.input {
height: 3.2em;
position: relative;
display: flex;
align-items: center;
font-size: 1em;
}
.input-control {
flex: 1;
z-index: 2; /* So that it is always "above" the label */
border: none;
padding: 0 0 0 1em;
background: transparent;
position: relative;
}
.input-label {
position: absolute;
top: 50%;
right: 0;
bottom: 0;
left: 1em; /* Align this with the control's padding */
z-index: 1;
display: none; /* Hide this for old browsers */
transform-origin: top left;
text-align: left;
}
For modern browsers, we can effectively disable the placeholder by setting its color to transparent. We can also align the input and the label relative to one other for when the placeholder is shown. To that end, we can also utilize the sibling selector in order to style the label with respect to the state of the input.
Finally, the trick! Exactly like above, we override the styles for the label and the input for modern browsers and the state where the placeholder is not shown. That involves moving the label out of the way and shrinking it a little.
Fundamentally, this technique requires a selector that matches nothing. To that end, we have been using :not(*); however, its support is also limited. The universal selector * is supported even by IE 7, whereas the :not pseudo-class has only been implemented since IE 9, which is thus the oldest browser in which this approach works. Older browsers would reject our selector groups for the wrong reason — they do not support :not! Alternatively, we could use a class selector such as .foo or a type selector such as foo, thereby supporting even the most ancient browsers. Nevertheless, these make the code less readable as they do not convey that they should never match anything, and thus for most modern sites, :not(*) seems like the best option.
As for whether the property of groups of selectors that we have been taking advantage of also holds in older browsers, the behavior is illustrated in an example as a part of the CSS 1 section on forward-compatible parsing. Furthermore, the CSS 2.1 specification then explicitly mandates this behavior. To put the age of this specification in perspective, this is the one that introduced :hover. In short, while this technique has not been extensively tested in the oldest or most obscure browsers, its support should be extremely wide.
Lastly, there is one small caveat for Sass users (Sass, not SCSS): upon encountering the :not(*):placeholder-shown selector, the compiler gets fooled by the leading colon, attempts to parse it as a property, and when encountering the error, it advises the developer to escape the selector as so: \:not(*):placeholder-shown, which does not look very pleasant. A better workaround is perhaps to replace the backslash with yet another universal selector to obtain *:not(*):placeholder-shown since, as per the specification, it is implied anyway in this case.
Dependencies in JavaScript are pretty straightforward. I can’t write library.doThing() unless library exists. If library changes in some fundamental way, things break and hopefully our tests catch it.
Dependencies in CSS can be a bit more abstract. Robin just wrote in our newsletter how the styling from certain classes (e.g. position: absolute) can depend on the styling from other classes (e.g. position: relative) and how that can be — at best — obtuse sometimes.
Design has dependencies too, especially in design systems. Nathan Curtis:
You release icon first, and then other components that depend on it later. Then, icon adds minor features or suffers a breaking change. If you update icon, you can’t stop there. You must ripple that change through all of icon’s dependent in the library too.
“If we upgrade and break a component, we have to go through and fix all the dependent components.” — Jony Cheung, Software Engineering Manager, Atlassian’s Atlaskit
The biggest changes happen with the smallest components.
.email::before {
content: attr(data-done) " Email: "; /* This gets inserted before the email address */
}
The property generally takes anything you drop in there. However, there are some invalid values it won’t accept. I heard from someone recently who was confused by this, so I had a little play with it myself and learned a few things.
This works fine:
/* Valid */
::after {
content: "1";
}
…but this does not:
/* Invalid, not a string */
::after {
content: 1;
}
I’m not entirely sure why, but I imagine it’s because 1 is a unit-less number (i.e. 1 vs. 1px) and not a string. You can’t trick it either! I tried to be clever like this:
But of course, you’d never use generated content for important information like a price, right?! (Please don’t. It’s not very accessible, nor is the text selectable.)
Even though you can get and display that number, it’s just a string. You can’t really do anything with it.
Heads up! Don’t try concatenating strings like you might in PHP or JavaScript:
/* These will break */
::after {
content: "1" . "2" . "3";
content: "1" + "2" + "3";
/* Use spaces */
content: "1" "2" "3";
/* Or nothing */
content: "1 2 3";
/* The type of quote (single or double) doesn't matter, but content not coming back from attr() does need to be quoted. */
}
There is a thing in the spec for converting attributes into the actual type rather than treating them all like strings…
<wood length="12" />
wood {
width: attr(length em); /* or other values like "number", "px", or "url" */
}
…but I’m fairly sure that isn’t working anywhere yet. Plus, it doesn’t help us with pseudo elements anyway, since strings already work and numbers don’t.
The person who reached out to me over email was specifically confused why they were unable to use calc() on content. I’m not sure I can help you do math in this situation, but it’s worth knowing that pseudo elements can be counters, and those counters can do their own limited form of math. For example, here’s a counter that starts at 12 and increments by -2 for each element at that level in the DOM.
The only other thing we haven’t mentioned here is that a pseudo element can be an image. For example:
p:before {
content: url(image.jpg);
}
…but it’s weirdly limited. You can’t even resize the image. ¯\_(ツ)_/¯
Much more common is using an empty string for the value (content: "";) which can do things like clear floats but also be positioned, sized and have a background of its own.
There is a such thing as an indeterminate checkbox value. It’s a checkbox (<input type="checkbox">) that isn’t checked. Nor is it not checked. It’s indeterminate.
We can even select a checkbox in that state and style it with CSS!
Some curious points though:
It’s only possible to set via JavaScript. There is no HTML attribute or value for it.
It doesn’t POST (or GET or whatever else) or have a value. It’s like being unchecked.
And, for whatever reason, you make that checkbox indeterminate:
let veg = document.querySelector(".veg");
veg.indeterminate = true;
If you serialize that form and take a look at what will POST, you’ll get "name=Chris". No value for the checkbox. Conversely, had you checked the checkbox in the HTML and didn’t touch it in JavaScript, you’d get "name=Chris&vegetarian=on".
Apparently, this is by design. Checkboxes are meant to be boolean, and the indeterminate value is just an aesthetic thing meant to indicate that visual „child” checkboxes are in a mixed state (some checked, some not). That’s fine. Can’t change it now without serious breakage of websites.
But say you really need to know on the server if a checkbox is in that indeterminate state. The only way I can think of is to have a buddy hidden input that you keep in sync.
let veg = document.querySelector(".veg");
let veg_value = document.querySelector(".veg-value");
veg.indeterminate = true;
veg_value.value = "indeterminate";
I’ve set the indeterminate value of one input and I’ve set another hidden input value to "indeterminate", which I can POST. Serialized means it looks like "name=Chris&vegetarian-value=indeterminate". Good enough.
There is a such thing as an indeterminate checkbox value. It’s a checkbox (<input type="checkbox">) that isn’t checked. Nor is it not checked. It’s indeterminate.
We can even select a checkbox in that state and style it with CSS!
Some curious points though:
It’s only possible to set via JavaScript. There is no HTML attribute or value for it.
It doesn’t POST (or GET or whatever else) or have a value. It’s like being unchecked.
And, for whatever reason, you make that checkbox indeterminate:
let veg = document.querySelector(".veg");
veg.indeterminate = true;
If you serialize that form and take a look at what will POST, you’ll get "name=Chris". No value for the checkbox. Conversely, had you checked the checkbox in the HTML and didn’t touch it in JavaScript, you’d get "name=Chris&vegetarian=on".
Apparently, this is by design. Checkboxes are meant to be boolean, and the indeterminate value is just an aesthetic thing meant to indicate that visual „child” checkboxes are in a mixed state (some checked, some not). That’s fine. Can’t change it now without serious breakage of websites.
But say you really need to know on the server if a checkbox is in that indeterminate state. The only way I can think of is to have a buddy hidden input that you keep in sync.
let veg = document.querySelector(".veg");
let veg_value = document.querySelector(".veg-value");
veg.indeterminate = true;
veg_value.value = "indeterminate";
I’ve set the indeterminate value of one input and I’ve set another hidden input value to "indeterminate", which I can POST. Serialized means it looks like "name=Chris&vegetarian-value=indeterminate". Good enough.
There’s a ton of very quotable stuff from Rachel Andrew’s latest post all about CSS and how we talk about it in the community:
CSS has been seen as this fragile language that we stumble around, trying things out and seeing what works. In particular for layout, rather than using the system as specified, we have so often exploited things about the language in order to achieve far more complex layouts than it was ever designed for. We had to, or resign ourselves to very simple looking web pages.
Rachel goes on to argue that we probably shouldn’t disparage CSS for being so weird when there are very good reasons for why and how it works — not to mention that it’s getting exponentially more predictable and powerful as time goes by:
There is frequently talk about how developers whose main area of expertise is CSS feel that their skills are underrated. I do not think we help our cause by talking about CSS as this whacky, quirky language. CSS is unlike anything else, because it exists to serve an environment that is unlike anything else. However we can start to understand it as a designed language, with much consistency. It has codified rules and we can develop ways to explain and teach it, just as we can teach our teams to use Bootstrap, or the latest JavaScript framework.
I tend to feel the same way and I’ve been spending a lot of time thinking about how best to reply to folks that argue that “CSS is dumb and weird.” It can sometimes be a demoralizing challenge, attempting to explain why your career and area of expertise is a useful one.
I guess the best way to start doing that is to stand up and say, “No, CSS is not dumb and weird. CSS is awesome!”
WordPress 5.0 is quickly approaching, and the new Gutenberg editor is coming with it. There’s been a lot of discussion in the WordPress community over what exactly that means for users, designers, and developers. And while Gutenberg is sure to improve the writing experience, it can cause a bit of a headache for developers who now need to ensure their plugins and themes are updated and compatible.
One of the clearest ways you can make sure your theme is compatible with WordPress 5.0 and Gutenberg is to add some basic styles for the new blocks Gutenberg introduces. Aside from the basic HTML blocks (like paragraphs, headings, lists, and images) that likely already have styles, you’ll now have some complex blocks that you probably haven’t accounted for, like pull quotes, cover images, buttons, and columns. In this article, we’re going to take a look at some styling conventions for Gutenberg blocks, and then add our own styles for Gutenberg’s Columns block.
Block naming conventions
First things first: how are Gutenberg blocks named? If you’re familiar with the code inspector, you can open that up on a page using the block you want to style, and check it for yourself:
The Gutenberg Pull Quote block has a class of wp-block-pullquote.
Now, it could get cumbersome to do that for each and every block you want to style, and luckily, there is a method to the madness. Gutenberg blocks use a form of the Block, Element, Modifier (BEM) naming convention. The main difference is that the top level for each of the blocks is wp . So, for our pull quote, the name is wp-block-pullquote. Columns would be wp-block-columns, and so on. You can read more about it in the WordPress Development Handbook.
Class name caveat
There is a small caveat here in that the block name may not be the only class name you’re dealing with. In the example above, we see that the class alignright is also applied. And Gutenberg comes with two new classes: alignfull and alignwide. You’ll see in our columns that there’s also a class to tell us how many there are. But we’ll get to that soon.
Applying your own class names
Gutenberg blocks also give us a way to apply our own classes:
The class added to the options panel in the Gutenberg editor (left). It gets applied to the element, as seen in DevTools (right).
This is great if you want to have a common set of classes for blocks across different themes, want to apply previously existing classes to blocks where it makes sense, or want to have variations on blocks.
Much like the current (or “Classic”) WordPress post editor, Gutenberg makes as few choices as possible for the front end, leaving most of the heavy lifting to us. This includes the columns, which basically only include enough styles to make them form columns. So we need to add the padding, margins, and responsive styles.
Styling columns
Time to get to the crux of the matter: let’s style some columns! The first thing we’ll need to do is find a theme that we can use. There aren’t too many that have extensive Gutenberg support yet, but that’s actually good in our case. Instead, we’re going to use a theme that’s flexible enough to give us a good starting point: Astra.
Astra is available for free in the WordPress Theme Directory. (Source)
Astra is a free, fast, and flexible theme that has been designed to work with page builders. That means that it can give us a really good starting template for our columns. Speaking of which, we need some content. Here’s what we’ll be working with:
Our columns inside the Gutenberg editor.
We have a three-column layout with images, headings, and text. The image above is what the columns look like inside the Gutenberg editor. Here’s what they look like on the front end:
Our columns on the front end.
You can see there are a few differences between what we see in the editor and what we see on the front end. Most notably, there is no spacing in between the columns on the front end. The left end of the heading on the front end is also lined up with the left edge of the first column. In the editor, it is not because we’re using the alignfull class.
Note: For the sake of this tutorial, we’re going to treat .alignfull, .alignwide, and no alignment the same, since the Astra theme does not support the new classes yet.
How Gutenberg columns work
Now that we have a theme, we to answer the question: “how do columns in Gutenberg work?”
Until recently, they were actually using CSS grid, but then switched to flexbox. (The reasoning was that flexbox offers wider browser support.) That said, the styles are super light:
We’ve got a pen with the final styles if you want to see the result we are aiming for. You can see in it that Gutenberg is only defining the flexbox and then stating each column should be the same length. But you’ll also notice a couple of other things:
The parent container is wp-block-columns.
There’s also the class has-3-columns, noting the number of columns for us. Gutenberg supports anywhere from two to six columns.
The individual columns have the class wp-block-column.
This information is enough for us to get started.
Styling the parents
Since we have flexbox applied by default, the best action to take is to make sure these columns look good on the front end in a larger screen context like we saw earlier.
First and foremost, let’s add some margins to these so they aren’t running into each other, or other elements:
/* Add vertical breathing room to the full row of columns. */
.wp-block-columns {
margin: 20px 0;
}
/* Add horiztonal breathing room between individual columns. */
.wp-block-column {
margin: 0 20px;
}
Since it’s reasonable to assume the columns won’t be the only blocks on the page, we added top and bottom margins to the whole parent container so there’s some separation between the columns and other blocks on the page. Then, so the columns don’t run up against each other, we apply left and right margins to each individual column.
Columns with some margins added.
These are starting to look better already! If you want them to look more uniform, you can always throw text-align: justify; on the columns, too.
Making the columns responsive
The layout starts to fall apart when we move to smaller screen widths. Astra does a nice job with reducing font sizes as we shrink down, but when we start to get around 764px, things start to get a little cramped:
Our columns at 764px wide.
At this point, since we have three columns, we can explicitly style the columns using the .has-3-columns class. The simplest solution would be to remove flexbox altogether:
This would automatically convert our columns into blocks. All we’d need to do now is adjust the padding and we’re good to go — it’s not the prettiest solution, but it’s readable. I’d like to get a little more creative, though. Instead, we’ll make the first column the widest, and then the other two will remain columns under the first one.
This will only work depending on the content. I think here it’s forgivable to give Yoda priority as the most notable Jedi Master.
In the first few lines after the media query, we’re targeting .has-3-columns to change the flex-flow to row wrap. This will tell the browser to allow the columns to fill the container but wrap when needed.
Then, we target the first column with .wp-block-column:first-child and we tell the browser to make the flex-basis 100%. This says, “make the first column fill all available space.” And since we’re wrapping columns, the other two will automatically move to the next line. Our result is this:
Our newly responsive columns.
The nice part about this layout is that with row wrap, the columns all become full-width on the smallest screens. Still, as they start to get hard to read before that, we should find a good breakpoint and set the styles ourselves. Around 478px should do nicely:
This removes the flex layout, and reverses the margins on the individual columns, maintaining the spacing between them as they move to a stacked layout.
Our small screen layout.
Again, you can see all these concepts come together in the following demo:
So, there you have it! In this tutorial, we examined how Gutenberg’s Columns block works, it’s class naming conventions, and then applied basic styles to make the columns look good at every screen size on the front end. From here, you can take this code and run with it — we’ve barely scratched the surface and you can do tons more with the CSS alone. For example, I recently made this pricing table using only Gutenberg Columns:
And, of course, there are the other blocks. Gutenberg puts a lot of power into the hands of content editors, but even more into the hands of theme developers. We no longer need to build the infrastructure for doing more complex layouts in the WordPress editor, and we no longer need to instruct users to insert shortcodes or HTML to get what need on a page. We can add a little CSS to our themes and let content creators do the rest.
If you want to get more in-depth into preparing your theme for Gutenberg, you can check out my course, Theming with Gutenberg. We go over how to style lots of different blocks, set custom color palettes, block templates, and more.
Let’s say you wanted to move the background-position on an element as you mouse over it to give the design a little pizzazz. You have an element like this:
<div class="module" id="module"></div>
And you toss a background on it:
.module {
background-image: url(big-image.jpg);
}
You can adjust the background-position in JavaScript like this:
Here’s an example that moves the background directly in JavaScript, but with a transition applied so it slides to the new position rather than jerking around the first time you enter:
Or, you could move an actual element instead (rather than the background-position). You’d do this if there is some kind of content or interactivity on the sliding element. Here’s an example of that, which sets CSS custom properties again, but then actually moves the element via a CSS translate() and a calc() to temper the speed.
I’m sure there are loads of other ways to do this — a moving SVG viewBox, scripts controlling a canvas, webGL… who knows! If you have some fancier ways to handle this, link ’em up in the comments.
With our robust SDK, super clean dashboard, detailed documentation, and world-class support, HelloSign API is one of the most flexible and powerful APIs on the market. Start building for free today.