.child element with class selected should be on top of other .child elements, each .child is inside .parent element with absolute position

Given the html and css below, is it possible to have a .child with class selected appear on top of other .child elements? I’d like if you can give an answer that would not change html structure and css position property of .child and .parent. Also would be great to not toggle anything on parent, it is better to toggle child classes or styles, for parent it is better to set it once.

.parent {     position: absolute; } .child {     position: relative; }
  <div>     <div>         <div class="parent">             <div class="child selected"></div>         </div>         <div class="parent">             <div class="child"></div>         </div>     </div> </div>

Greatly appreciate any input, thank you.

Asked on July 16, 2020 in CSS.
Add Comment
1 Answer(s)

If you really want to stick to this HTML structure you could as example hide all elements (children) and show them only when they are selected.

A better solution would be having the selected class on the parent so then you could just simply give the selected parent a higher z-index.

Here you can find a snippet of how you can toggle the display without touching the HTML

// for demo purpuses var toggleLayer = function() {   var next = $('.child.selected').removeClass('selected').closest('.parent').next();   var element = next.length ? next : $('.parent:first-child');   element.find('.child').addClass('selected') }
.parent {   position: absolute; } .child {   position: relative;   display: none; }  .selected {  display: block; }   /* for demo purpuses */ .child {   height: 100px;   width: 100px;   line-height: 100px;   text-align: center;   background: red; }  button {   position: fixed;   top: 120px;   left: 10px; }
<div>   <div>     <div class="parent">       <div class="child selected">1</div>     </div>     <div class="parent">       <div class="child">2</div>     </div>     <div class="parent">       <div class="child">3</div>     </div>     <div class="parent">       <div class="child">4</div>     </div>   </div> </div>  <!--- FOR DEMO PURPUSES ---> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button onClick="toggleLayer()">Toggle layer</button>

Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.