Reputation: 267
I am beginner in web development, and i am trying to develop a responsive website. While developing i made one div element that has an image, then inside that i have one box with content "BUILD THAT MATTERS", which is inside a div with a class "firstBlock", the div "firstBlock" moves down when i click the hover button of navigation bar, but the box inside "BUILD THAT MATTERS", doesn't move.
I tried to make the image as a background image of the the div firstBlock, but that made the fitting of image in such a way that it got cropped, so is there any way so that the box inside the div moves with the navigation bar drop down menu, as of now only the firstBlock, that is the image moves, but inner box "BUILD THAT MATTERS" remains fixed in its position.
<-- html-->
<div id="firstBlock">
<img id="img1" src="image1.jpg">
<div class="box1">
<h1 class="text1">BUILD THAT MATTERS</h1>
</div>
</div>
/*CSS*/
#firstBlock {
display: flex;
height: 90%;
width: 100%;
}
#img1 {
width: 100%;
height: 100%;
object-fit: cover;
}
.box1 {
display: flex;
border: 5px solid black;
position: absolute;
top: 70%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
So, the box with content "BUILD THAT MATTERS" should move down with the first block when navigation drop down scrolls down.
fiddle link: https://jsfiddle.net/gj7v8huc/
git link: https://ayush-flash.github.io/StartupLandingPage/StartUpLandingPage/
Upvotes: 0
Views: 66
Reputation: 13998
It is all about parent and child element for using position:absolute
. Parent element should have relative
position so that the absolute
child element will do the calculation of top
and left
from its expected parent. So apply position:relative
to your firstBlock
div.
#firstBlock {
display: flex;
height: 90%;
width: 100%;
position:relative;
}
Also change your box1
div top and left position as per your parent alignment. I have applied 50% like below.
.box1 {
display: flex;
border: 5px solid black;
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
As I have already posted in the comment, below is the JSFiddle link.
Upvotes: 1
Reputation: 23824
Very simple rule: make the parent of the absolute element relative
Your class:
.box1 {
display: flex;
border: 5px solid black;
position: absolute; # parent of this should be relative
top: 40%; # I set this to 40%
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
the parent:
#firstBlock {
display: flex;
height: 90%;
width: 100%;
position: relative; # take care of child with absolute position
}
What is this rule for?
When we have an element that has position: absolute
it is removed from current flow of document. For bringing it back to the document's flow but meanwhile keeping it according to the need of absolute
position, we can make the parent's position relative
Upvotes: 1