BlackHoleGalaxy BlackHoleGalaxy - 1 year ago 74
Sass (Sass) Question

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?

Answer Source

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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download