Apply css to a parent element

6

I have the following code:

<div class="togglearea">
  <div class="toggle">
    <h3>Titulo</h3>
  </div>
</div>
<div class="togglearea">
 <div class="toggle">Titulo 2</div>
</div>

I have tried (as well as css and javascript ) failed that if the .togglearea has a h3 , apply the .togglearea a margin-left of 30px . But I only get the change to the h3 or all the .togglearea

    
asked by MarisabelGC 12.01.2017 в 21:45
source

1 answer

5

As I put you in a comment, only CSS can not be done because (at the moment) there is no selector for ancestors or superior brothers. With Javascript / jQuery it would be really simple, you could do something like this:

// selecciona todos los h3 que estén dentro de un togglearea
$(".togglearea h3").each(function() {
  // selecciona el .togglearea ancestro del h3 y pone el margen de 30
  $(this).closest(".togglearea").css("margin-left", "30px");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

<div class="togglearea"><div class="toggle"><h3>Titulo</h3></div></div>
<div class="togglearea"><div class="toggle">Titulo 2</div></div>

Although I said that it can not be done only with CSS, there is a way to do it without JS but certain restrictions must be fulfilled:

  • The h3 must be the first element.
  • Requires that there is nothing else outside the container of h3
  • The idea would be to set a margin of 30px for ALL the elements next to h3 using the sibling selector ~ . It would be something like this:

    .togglearea h3,
    .togglearea h3 ~ * {
      margin-left:30px;
    }
    <div class="togglearea"><div class="toggle"><h3>Titulo</h3></div></div>
    <div class="togglearea"><div class="toggle">Titulo 2</div></div>
        
    answered by 12.01.2017 / 21:57
    source