Responsive Styling Using Attribute Selectors


0

One of the challenges we face when implementing class-based atomic styling is that it often depends on a specific breakpoint for context.

 
 

It’s common to use a prefix to target each breakpoint:

This works well until we start adding multiple classes. That’s when it becomes difficult to keep a track what relates to what and where to add, remove. or change stuff.

We can try to make it more readable by re-grouping:

We can add funky separators (invalid class names will be ignored):

But this still feels messy and hard to grasp, at least to me.

We can get a better overview and avoid implementation prefixes by grouping attribute selectors instead of actual classes:


These aren’t lost of classes but a whitespace-separated list of attributes we can select using [attribute~="value"], where ~= requires the exact word to be found in the attribute value in order to match.

@media (min-width: 0) {
 [sm~="span-1"] { /*...*/ }              
 [sm~="span-2"] { /*...*/ }   
 /* etc. */ 
}
@media (min-width: 30rem) {
 [md~="span-1"] { /*...*/ }   
 [md~="span-2"] { /*...*/ }   
 /* etc. */   
}
@media (min-width: 60rem) {
 [lg~="span-1"] { /*...*/ }   
 [lg~="span-2"] { /*...*/ }   
 /* etc. */   
}

It may be a bit odd-looking but I think translating atomic classes to  attributes is fairly straightforward (e.g. .sm-span-1 becomes [sm~="span-1"]). Plus, attribute selectors have the same specificity as classes, so we lose nothing there. And, unlike classes, attributes can be written without escaping special characters, like /+.:?.

That’s all! Again, this is merely an idea that aims to make switching declarations in media queries easier to write, read and manage. It’s definitely not a proposal to do away with classes or anything like that.


Like it? Share with your friends!

0
admin