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
short answer is:
you need to use
position: relative
prop on your .divTwo, because: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)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 theposition
property of the containing div torelative
. This positions the#blue_square
element relative to its parent container. Here’s how you can modify your code:HTML:
CSS:
By setting the
divTwo
container’s position torelative
, you ensure that the#blue_square
element is positioned relative to thedivTwo
container. This means it will not overlap or interfere with other elements outside ofdivTwo
, such as theblueBackground
div.