Fake Conditional Statements in CSS

For a first post, let’s start this off simple. I saw a question on Reddit the other day asking if you could dynamically change the size of elements depending on what the user clicked on without using Javascript. [http://goo.gl/SErS9]

You can almost create this effect with CSS3 selectors and no Javascript at all.
Here is the CSS:

#div1, #div2
border:solid 1px #000000;
height:200px !important;
height:200px !important;

And the HTML:

<a href="conditional-test.html#div1">Link to Div1</a>

<a href="conditional-test.html#div2">Link to Div2</a>
<div id="div1">

<a name="div1">This is a bunch of data.</a>
This is more data you can't see yet.

<div id="div2">

<a name="div2">This is a bunch of other data.</a>
This is more data you can't see yet.


The first handy thing to point is the chunk of CSS that says div[id^=”div]

At first glace this might seem like unnecessary mark-up, but the carot symbol (^) is actually a CSS identifier that says “target anything that starts with.”

So in this case, I am looking to target divs ( div[id^=”div] ) whose ID starts with ( div[id^=“div] ) the word “div.” ( div[id^=”div] )

As you can see in the HTML I have to divs names “div1” and “div2” and this was just one way to target both of them. This becomes more effective the more elements you have that have similar names and share similar styles, but have their own variations or perhaps are dynamically generated by something like a C# control and they end up with weird additions to what were your nice cleanly defined classes.

At the top of the HTML, you can see that we have two links, each ending in a hash tag and the name of one of our divs. When these links are clicked on, that name is appended to the end of the URL and is referred to as the “target.”

This incorporates the final chunk of our CSS that pretty much says if there is a div on the page with the same name as this target in the URL, append this style which in this case happens to make the div tall enough to see the other sentence of content.

With this method you can’t do fun things like animating the application of styles, but the technique does work and is super simple to do if you want to implement it in a hurry.

Leave a Reply

Your email address will not be published. Required fields are marked *