Artem Z Artem Z - 4 months ago 9
CSS Question

CSS :before and sibling selector not working

I have the following markup, and I need to find a CSS way to change a triangle whenever .hide class is active.

To achieve this I've used a pseudo element like this:

summary:before {
content: '\25BC';
}
summary:before + .hide {
content: '\25BA';
}


The problem is: it doesn't work. The arrow doesn't change. Even though summary:before + .hide appears in the DevTools.

So how to achive the desired effect without using JavaScript only CSS?



var $div = $('summary');

$div.on('click', function() {
$('ul').toggleClass('hide');
});

.wrapper {
width: 300px;
height: 300px;
background-color: #ecf0f1;
}
.details {
outline: none;
background-color: #95a5a6;
cursor: pointer;
position: relative;
}
summary {
outline: none;
margin-left: 30px;
}
summary:before {
content: '\25BA';
font-size: 12px;
position: absolute;
top: 2px;
left: 13px;
}
summary:before + ul.hide {
content: '\25BC';
font-size: 12px;
position: absolute;
top: 2px;
left: 13px;
}
.hide {
display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="details">
<summary>Sample</summary>
<ul class="hide">
<li>
<input type="radio" checked/>
<label>Label 1</label>
</li>
<li>
<input type="radio" />
<label>Label 2</label>
</li>
<li>
<input type="radio" />
<label>Label 3</label>
</li>
</ul>
</div>
</div>




Answer

You can't select the previous element in CSS. Instead add a class to the div and toggle it.

Try below solution.

var $div = $('summary');

$div.on('click', function() {
  $('ul').toggleClass('hide');
  $(this).toggleClass('collapse');
});
.wrapper {
  width: 300px;
  height: 300px;
  background-color: #ecf0f1;
}
.details {
  outline: none;
  background-color: #95a5a6;
  cursor: pointer;
  position: relative;
}
summary {
  outline: none;
  margin-left: 30px;
}
summary:before {
  content: '\25BA';
  font-size: 12px;
  position: absolute;
  top: 2px;
  left: 13px;
}
summary.collapse:before {
  content: '\25BC';
}
.hide {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="details">
    <summary>Sample</summary>
    <ul class="hide">
      <li>
        <input type="radio" checked/>
        <label>Label 1</label>
      </li>
      <li>
        <input type="radio" />
        <label>Label 2</label>
      </li>
      <li>
        <input type="radio" />
        <label>Label 3</label>
      </li>
    </ul>
  </div>
</div>

Comments