Conditional Selectors in CSS Rock

I have been working on a web project that involves some HTML data that I can’t change statically, with the exception of some CSS modification abilities. Since I can’t make any adjustments to this software’s output of HTML data, or Javascript, I have been able to figure out cool little tricks to change things on the resulting HTML page by using CSS.

Take the following for example. There is a bar that is shown at the top of the page. This is styled with a DIV tag with no ID or NAME attribute. So it was initially hard for me to figure out how to catch this item and remove it. I figured out a way using a conditional selector in CSS.

Original line in HTML

<div style=background:url(/images/top-bar-bg.png) center repeat-x;height:32px;text-align:center;>
 <span style=background:url(/images/top-bar-icon.png) center left no-repeat;padding-left:30px;font-family:Arial, Helvetica, sans-serif;font-size:13px;font-weight:normal;color:#4a4a4a;display:inline-block;border:none;margin-top:4px;></span>
 </div>

How I hid this element using CSS Selector

div[style ^='background:url(/images/top-bar-bg.png)'] { display:none; visibility:hidden; }

This worked for me because I know that this is the only DIV element with this style attribute. Otherwise I think it would hide all the elements that match this.

An attribute selector will match elements on the basis of either the presence of an attribute, or the exact or partial match of an attribute value. Attribute selectors were introduced in CSS2, and CSS3 added a few more.

Attribute selectors are delimited by square brackets; the simplest form of an attribute selector consists of an attribute name surrounded by square brackets.

^= – starts with
$= – ends with
~= – matches any space separated words (foo bar baz)
|= – matches any hyphenated words (foo-bar, bar-baz)

I’m not a web developer, designer or geek. Just thought I’d share some sweet knowledge I just figured out.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.