Content aware CSS - apply style only if content is available

后端 未结 3 1011
后悔当初
后悔当初 2020-12-13 17:48

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 e

相关标签:
3条回答
  • 2020-12-13 18:09

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

    0 讨论(0)
  • 2020-12-13 18:19

    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

    0 讨论(0)
  • 2020-12-13 18:20

    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.

    0 讨论(0)
提交回复
热议问题