skip to Main Content

I am trying to understand how I to contain a CSS from one div from not starting over another div.

By that I mean, how can I place position: fixed on an item only inside a particular div?

For example here is my HTML and CSS and JS:

<div class="blueBackground"></div>

<div class="divTwo">
    <div class="col-md-12 col-sm-10">   
        <div id="blue_square" style="top: 310px;"></div>
    </div>   
</div>

#blue_square{
    position: fixed;
    right: 0;
    z-index: 9;
    width: 370px;
    box-shadow: 0 0 6px transparent;
}


$("#blue_square").css("top", $(window).height() / 2 - 90)

As you can see I have here to separate divs: blueBackground and divTwo.

The problem I am seeing is that my CSS from divTwo is somehow starting on from blueBackground div. Here is a snap shot: example 1.

I want the CSS for #blue_square to only apply within the divTwo not outside of it. Why is the "blue sqaure" diagram starting on blueBackground and not from within divTwo? I am trying to make it to look like this: example 2

Is there something I am missing in my css or Jquery?

2

Answers


  1. short answer is:
    you need to use position: relative prop on your .divTwo, because:

    all the position absolute elements will be placed "relative" to the
    closest position : relative parent it has.

    If there isn’t any parent with the position:relative prop, it will just be placed based on the body tag (as you are seeing in your case)

    Login or Signup to reply.
  2. If you want to ensure that the position: fixed element (#blue_square) remains within the boundaries of its containing div (divTwo), you can achieve this by setting the position property of the containing div to relative. This positions the #blue_square element relative to its parent container. Here’s how you can modify your code:

    HTML:

    <div class="blueBackground"></div>
    <div class="divTwo">
        <div class="col-md-12 col-sm-10">   
            <div id="blue_square"></div>
        </div>   
    </div>
    

    CSS:

    #blue_square {
        position: fixed;
        right: 0;
        z-index: 9;
        width: 370px;
        box-shadow: 0 0 6px transparent;
    }
    
    .divTwo {
        position: relative;
    }
    

    By setting the divTwo container’s position to relative, you ensure that the #blue_square element is positioned relative to the divTwo container. This means it will not overlap or interfere with other elements outside of divTwo, such as the blueBackground div.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search