mw_geq
Last Updated: February 25, 2016
·
1.197K
· jonah_stuart
Thumb jonah

Quick and Dirty Conditional Layouts With the Adjacent Selector

I’ve used the adjacent selector mostly as a tool to hit elements that I didn’t want to hit with a class, e.g. links following spans or paragraphs. But I had an exciting realization to use it as more of a conditional for page compositions.

Consider a typical layout.

<style>

  /*Your basic container with whatever width constraints you want*/
  .container{
    width: 100%;
  }

  /*Sidebar with a defined width*/
  #sidebar{
    float: left;
    width: 300px;
  }

  /*Flexible content box*/ 
  #content{
    margin-left: 300px;
    width: auto;
  }
</style>

<div class="container">
  <div id="sidebar"></div>
  <div id="content"></div>
</div> 

What does it mean?

So we’ve got our standard layout with a left sidebar (for an app, lets say). You could be questioning the float and the margin-left, and all that, but hold on.

Now this app has a ton of views and the #content container is a pretty generic but semantic ID I’d like to carry through even when the #sidebar isn’t in the DOM. I want this for a couple of reasons. Easier and less hyper specific style management at the container level, and I don’t want to add conditional classes on the #content per view. I’d hate to muddy up the DOM with presentation classes and the alternative of injecting the sidebar spacing styles per semantic #content class is even more of a headache.

Use the adjacent selector, it's super effective!

If you don't know the adjacent selector, it looks like this:

x + y { } 

What this does is find “x" in the DOM and grabs the “y” immediately proceeding it. You could also use the less strict “~” in place of the “+” to select any “y” proceeding the “x” if you need to grab more than just one.

Getting the gist? Let’s get wild and crazy and do… this!

.container{
  width: 100%;
}

#sidebar{
  float: left;
  width: 300px;
}

#content{
  width: auto;
} 

#sidebar + #container{
  margin-left: 300px;
}

Now, only if you have the #sidebar in the view will the #content have the conditional 300px margin, allowing the two to line up seamlessly. And when #sidebar isn't there, you get your nice full width #content with no extra effort.

Further reading on selectors.

Handy list of css selectors from tutsplus.

Say Thanks
Respond

1 Response
Add your response

12912
Myself2014

Yay! Never thought like this. Thanks for the idea, gonna have some crazy layout fun tonight)

over 1 year ago ·