Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Content aware CSS - apply style only if content is available

Tags:

html

css

Is it possible to have a css style be aware of whether the element it is being applied to has some sort of content or not? I am currently using tables (forced to since the end user uses cms to create pages) with a css for each cell, as so

<table>
<tr>
    <td class="someClass">Test value 1</td>
    <td class="someClass">Test value 2</td>
</tr>
<tr>
    <td class="someClass">Test value 3</td>
    <td class="someClass"></td>
</tr>
</table>

As displayed, there is the chance that a table cell is left empty. Is there a way to make "someClass" aware of this and not apply the style to this cell?

I am sure there is some js hack I could apply, but I wonder if it is possible with pure css. Long shot?

Thanks.

like image 997
mspir Avatar asked Jan 30 '12 11:01

mspir


3 Answers

Simply use the :empty pseudo-class like so:

td.someClass:not(:empty) {
    /* Styles */
}

As Petr Marek mentions it's not very reliable as a cross-browser solution, so if you must support older browsers (IE8 and older) you will need JS (which you can probably figure out yourself). Otherwise, the above CSS rule will work just fine.

You can find the browser compatibility of :not() and :empty here

like image 148
BoltClock Avatar answered Oct 18 '22 18:10

BoltClock


The only thing I can think of that relates to your question is psuedo-classes, such as empty. Here is an example:

<html>
  <head>
    <title>Example</title>
    <style type="text/css">
      .cell:not(:empty) {
        background-color: red;    
      }
      .cell:empty {
        background-color: blue;
      }
    </style>
  </head>
  <body>
    <table><tBody>
      <tr><td class="cell"></td><td class="cell">Not empty</td></tr>
      <tr><td class="cell">Not empty</td><td class="cell"></td></tr>
    </tBody></table>
  </body>
</html>

In modern browsers, you will see that empty cells are blue and cells with content are red. The key here is the first line of CSS, .cell:not(:empty). This applies the CSS if the element does not have the psuedo-class :empty applied.

like image 21
Shane Avatar answered Oct 18 '22 19:10

Shane


No, with pure cross-browser css it is not. You will have to edit their cms or use javascript.

like image 42
mreq Avatar answered Oct 18 '22 20:10

mreq