O'Reilly

CSS Preprocessors and Parent Selectors

By on  

Working on web sites and web apps that require RTL support is hard because ensuring correct display in RTL is made more difficult by the fact that we either don't have the CSS properties and values to do so or that the existing support isn't widely used enough yet.  We have values like start for text-align and we have properties like -moz-margin-start, but they aren't supported everywhere despite knowing that RTL is an important aspect of global sites.

So what do we ultimately have to do?  Repeat selectors with a new RTL value and sometimes even an offset:

/* ltr / default */
.some {
	.thing {
		> .is {
			.here {
				margin-left: 20px;
			}
		}
	}
}

/* rtl */
html[dir=rtl] {
	.some {
		.thing {
			> .is {
				.here {
					margin-right: 20px;
					margin-left: 0;
				}
			}
		}
	}
}

I consider this a nightmare for a few reasons:

  1. If you have to change the default nested CSS structure, you must remember to do so for the separate RTL block as well
  2. If you have to offset the original rule, you're required to remember to offset the original and then set the new rule

In tinkering with Stylus, I've found an excellent solution for curing all of these problems with a simple mixin:

/* mixin definition ; sets LTR and RTL within the same style call*/
bidi-style(prop, value, inverse-prop, default-value) {
	{prop}: value;

	html[dir=rtl] & {
		{inverse-prop}: value;
		{prop}: default-value;
	}
}

/* usage */
.some {
	.thing {
		> .is {
			.here {
				bidi-style(margin-left, 20px, margin-right, 0); /* setting LRT and RTL! */
			}
		}
	}
}

The mixin above is a simple but sends me into a state of euphoria.  Instead of having to copy and maintain the nested structure, this mixin allows me to set the property values for LTR and RTL in the same place in code, avoiding the need to create separate RTL blocks.  And this scenario, of simply swapping out properties depending on direction, covers 95% of direction scenarios.

I know that LESS also accommodates for this pattern but I'm not sure if SASS does as well.  What's also nice is that RTL isn't the only scenario where this is useful; you could also use this for feature-based stuff like Modernizr CSS classes:

.gradient-background {
	background-image: linear-gradient(top, #555, #333);

	.no-cssgradients & {
		background: url("background.png")
	}
}

Brilliant!  This simple structure makes coding CSS and organizing different states a million times easier.  In an ideal world, the "start" properties and values would be in place but until then, use this type of strategy to make your life easier!

Track.js Error Reporting

Upcoming Events

Recent Features

  • How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

  • Detect DOM Node Insertions with JavaScript and CSS Animations

    I work with an awesome cast of developers at Mozilla, and one of them in Daniel Buchner. Daniel's shared with me an awesome strategy for detecting when nodes have been injected into a parent node without using the deprecated DOM Events API....

Incredible Demos

  • WebKit Marquee CSS:  Bringin’ Sexy Back

    We all joke about the days of Web yesteryear.  You remember them:  stupid animated GIFs (flames and "coming soon" images, most notably), lame counters, guestbooks, applets, etc.  Another "feature" we thought we had gotten rid of was the marquee.  The marquee was a rudimentary, javascript-like...

  • Create a Photo Stack Effect with Pure CSS Animations or MooTools

    My favorite technological piece of Google Plus is its image upload and display handling.  You can drag the images from your OS right into a browser's DIV element, the images upload right before your eyes, and the albums page displays a sexy photo deck animation...

Discussion

  1. yes, SASS does support that pattern too. even the last time I used less, it doesn’t work but it was a long time ago.

  2. As Bobby said it’s fairly easy in SASS as well. Required a few tweaks but here is a SASS version for those interested http://codepen.io/fleeting/pen/AqHtu.

  3. Denis Borovikov

    You can upgrade bidi-style mixin, if make function like compass opposite-position() http://compass-style.org/reference/compass/helpers/constants/

    There is no need to pass inverse property, because you always can calculate it from property itself.

  4. André Machado

    Nice aproach.

    I am Brazilian but work in Dubai (UAE), have the constant need to work with “rtl / ltr” but had not yet achieved an elegant way to work with exceptions to “rtl” rules.

    Thanks for the tip!

  5. Also have such functions in Sass,like this:

    Sass:

    @mixin bidi-style($prop,$value,$inverse-prop,$default-value){
    	#{$prop}: $value;
    	html[dir=rtl] : $value;
    		#{$prop}: $default-value;
    	}
    }
    
    .some {
    	.thing {
    		> .is {
    			.here {
    				@include bidi-style(margin-left,20px,margin-right,0);
    			}
    		}
    	}
    }
    

    Compiled in the CSS:

    .some .thing > .is .here {
      margin-left: 20px; }
      html[dir=rtl] .some .thing > .is .here {
        margin-right: 20px;
        margin-left: 0; }
    

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Free Download: Font Bundle Featuring 17 Incredible Typefaces

    The only thing we love more than a good font, is a good free font. So we’ve combed the Web for some of our favorite free fonts, and gathered them here in a single download. You’ll find a variety of useful typefaces, from highly geometric designs...

  • OâReilly Velocity Conference â Amsterdam

    My favorite front-end conference has always been O'Reilly's Velocity Conference because the conference series has focused on one of the most undervalued parts of client side coding:  speed.  So often we're so excited that our JavaScript works that we forget that speed, efficiency, and performance are just as important. The next Velocity...

  • CanIUse Command Line

    Every front-end developer should be well acquainted with CanIUse, the website that lets you view browser support for browser features.  When people criticize my blog posts for not detailing browser support for features within the post, I tell them to check CanIUse:  always up to date, unlike...

  • Generating Alternative Stylesheets for Browsers Without @media

    If your CSS code is built with a mobile-first approach, it probably contains all the rules that make up the "desktop" view inside @media statements. That's great, but browsers that don't support media queries (IE 8 and below) will simply ignore them, ending up getting the...

  • Serve a Directory with PHP

    Many developers have a giggle at PHP, even looking down at the language, but let's be honest:  most of our blogs are powered by it (WordPress) and it's a great language to dabble around with.  I cut my teeth on PHP, though I prefer to avoid PHP these days. But...