MyName
MyName

Reputation: 367

Css Change color of element by click on the other element

I have pagination How can I change background of pagination__link with text "left" when click on the other links? It is necessary to use only CSS.

Upvotes: 0

Views: 69

Answers (2)

David Thomas
David Thomas

Reputation: 253318

You can do this, but frankly it's messy, using CSS flexible-boxes along with the relatively new :focus-within pseudo-class. This does require reversing the order of <li> elements within the <ul> however:

.pagination {
  /* sets the display to use the flex layout: */
  display: flex;
  /* ensures the contents of the <ul> are shown in
     columns and in reverse-order: */
  flex-direction: column-reverse;
}

/* selects first the <li> that has a focused element
   within it, then finds all subsequent <li> elements,
   using the general-sibling combinator ('~') that
   also matches the :last-child pseudo-class (there can,
   obviously, be only one) then finds the <a> element(s)
   which is a child of that <li> element: */
li:focus-within ~ li:last-child > a {
  background - color: red;
}
<ul class="pagination">
  <li class="pagination__item pagination__item--active">
    <a class="pagination__link" href="#">
      Page 2
    </a>
  </li>
  <li class="pagination__item">
    <a class="pagination__link" href="#">
      Page 1
    </a>
  </li>
  <li class="pagination__item">
    <a class="pagination__link" href="#">
          left
        </a>
  </li>
</ul>

External JS Fiddle demo.

References:

Upvotes: 1

kyun
kyun

Reputation: 10264

input[name="radio"]{
  display: none;
}
label{
  text-decoration: underline;
  color: blue;
}

input[name="radio"]:checked + label{
  background-color: yellow;
}
<ul class="pagination">
  <li class="pagination__item">
    <input type="radio" id="radio1" name="radio" />
    <label for="radio1">left</label>
    <!--
    <a class="pagination__link" href="#">  
      left
    </a>
    -->
  </li>
  <li class="pagination__item">
    <input type="radio" id="radio2" name="radio" />
    <label for="radio2">Page1</label>
    <!--
    <a class="pagination__link" href="#">
      Page 1
    </a>
    -->
  </li>
  <li class="pagination__item pagination__item--active">
    <input type="radio" id="radio3" name="radio" />
    <label for="radio3">Page1</label>
    <!--
    <a class="pagination__link" href="#">
      Page 2
    </a>
    -->
  </li>
</ul>

Maybe it's not the answer what you want.

But I think it can be good hint for your problem.

You can use the checkbox trick or radio trick.

Upvotes: 0

Related Questions