简体   繁体   中英

How to select a selector when a class does not exists

I have a doubt about the "sibling selectors" for CSS.

This is the situation:

if in some countries we can show the header but in other countries must not show the header, for example:

<!-- USA page -->
<div class="body">
  <div class="header">HEADER</div> <!-- it exists -->
  <div class="wrapper">BODY</div>
</div>

<hr>

<!-- Canada page --> <!-- does not have header -->
<div class="body">
  <div class="wrapper">BODY</div> <!-- I want to modify this wrapper -->
</div>

I am not sure if it's possible because I can't create a new style for the <div class="wrapper">BODY</div> only for Canada because it's one template for all countries.

it's a twig template

<div class="body">
  {% if show-header %} <!-- if true show -->
    <div class="header">HEADER</div>
  {% endif %}
  <div class="wrapper">BODY</div>
</div>

so...I need a purely CSS solution... How I can have a specific style to apply for <div class="wrapper">BODY</div> if the <div class="header">HEADER</div> does not exist in Canada. let's say to change the color of the BODY but not for USA.

I thought that with selector to the :not() pseudo-class like so:

:not(.printable) {
    /* Styles */
}

but, what is the approach?

I'm not a pro in twig, but you can play around with conditional classes:

<div class="body">
  {% if show-header %} <!-- if true show -->
    <div class="header">HEADER</div>
  {% endif %}
  <div class="{{ country == 'Canada' ? 'wrapper-canada' : 'wrapper-usa' }}">BODY</div>
</div>

Or even use function where you will identify country and return corresponding class name.

If I understand your question, a sibling selector would still work for you. Your sibling selector (the presence of .header ) would be an override.

So something like this:

.body .wrapper {
  color: red; // Default color
}
.body .header + .wrapper {
color: blue; // Override default color when sibling exists
}

JSFiddle: https://jsfiddle.net/fch3drve/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM