Search code examples
javascriptjqueryhtmlcssz-index

clipping labels with z-index


I have the vertical label "PINK" aligned in the middle of a section. When I scroll down to the next section the "PINK" is being covered by the next section which is having an higher z-index.

div.back1 {
    background-color: #FF00FF;
    position: relative;
    width: 100%;
    height: 2000px;
    z-index: 10;
}
div.text1 {
	transform: rotate(-90deg);
    position: fixed;
    top: 50%;
    background-color: #FFFFFF;
    z-index: 20;
}
div.back2 {
    background-color: #0000FF;
    position: relative;
    width: 100%;
    height: 2000px;
    z-index: 30;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<div class="text1">PINK</div>
<div class="back1"></div>
<div class="back2"></div>

</body>
</html>

I would like to have a second title "BLUE" in the second section to appear as shown in the following mockup.

enter image description here

Is it possible to arrange the z-indexes to achieve this result? Is there another better way to clip the labels, keeping their alignment at 50% of the viewport?

Thanks a lot in advance for any contribution!


Solution

  • Try this code

    since you tagged jquery,i used it to add class fixed

    $(document).ready(function(){
    $('.blue-text').hide();
    $(window).scroll(function() {
    if ($('.blue').offset().top <= $('.pink-text').offset().top + 40)
    {
      $('.blue-text').show();
      if($('.blue').offset().top <= $('.pink-text').offset().top){
         $('.blue-text').addClass('fixed');
      }
    }
    else{
      $('.blue-text').removeClass('fixed');
      $('.blue-text').hide();
    }
    });
    });
    div.back1 {
        background-color: #FF00FF;
        position: relative;
        width: 100%;
        height: 2000px;
        z-index: 10;
    }
    div.text1.fixed {
    	transform: rotate(-90deg);
        position: fixed;
        top: 50%;
        background-color: #FFFFFF;
        z-index: 20;
    }
    div.back2 {
        background-color: #0000FF;
        position: relative;
        width: 100%;
        height: 2000px;
        z-index: 30;
    }
    .blue,.pink {
        position: relative;
    }
    .text1 {
        position: absolute;
        top: 10px;
        z-index: 31;
        transform: rotate(-90deg);
        background-color: #FFFFFF;
    }
    .text1.blue-text.fixed{
        z-index: 31;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <div class="color">
    <div class="pink">
    <div class="text1 pink-text fixed">PINK</div>
    <div class="back1"></div>
    </div>
    <div class="blue">
    <div class="text1 blue-text">BLUE</div>
    <div class="back2"></div>
    </div>
    </div>