BlackHoleGalaxy
BlackHoleGalaxy

Reputation: 9672

Style an element only when there is no h1 sibling element

I have two sets of markup on my page:

<div class="row">
    <div>Some random div(s)</div>
    <table></table>
</div>

and

<div class="row">
    <div>Some random div(s)</div>
    <h1>Table Title</h1>
    <table></table>
</div>

I would like to apply margin-top and some other CSS customizations to div.row > table when there is no h1 in div.row. For example, in the above markup the first table would be styled but the second would not.

I can't find a convenient way to setup a rule for that set of conditions. I'm quite new to SASS and don't want to have to add a specific class to the table element.

Do you have any tips on what to do to achieve this?

Upvotes: 2

Views: 346

Answers (2)

Hidden Hobbes
Hidden Hobbes

Reputation: 14183

As you are looking to style a table which always appears after an adjacent h1 element this is achievable in CSS by using a combination of the :not() and next-sibling (+) selectors.

.row > :not(h1) + table

The rule will match any table element which is directly preceded by an element which is not an h1 which is an immediate child of an element with the class .row.

.row > :not(h1) + table {
  border: 1px solid blue;
  margin-top: 10px;
}
<div class="row">
  <div>Some random div(s)</div>
  <table>
    <tr>
      <td>This will match the rule</td>
    </tr>
  </table>
</div>
<div class="row">
  <div>Some random div(s)</div>
  <h1>Table Title</h1>
  <table>
    <tr>
      <td>This will not match the rule</td>
    </tr>
  </table>
</div>

Upvotes: 2

Matt Spinks
Matt Spinks

Reputation: 6700

SASS ultimately compiles down to CSS, and according to the CSS rules, such a selector is not possible. You will have to do it via scripting (javascript, jQuery). There have been a lot of questions about this. Check these references:

Apply CSS styles to an element depending on its child elements

CSS selector for “foo that contains bar”?

Is there a CSS parent selector?

Finally, check this link for the reasons why we don't have the parent selector option.

Upvotes: 2

Related Questions