so, I have a confusion about the behavior of top
and bottom
when we apply position: relative;
on a div.
here is my code snippet:
*{
margin:0;
padding:0;
box-sizing:border-box;
}
.parent{
border:1px solid red;
height: 200px;
width:200px;
margin:100px;
}
.relative{
background:#ff0;
height: 100px;
width:100px;
position:relative;
top:100px;
right:100px;
left:100px;
bottom:200px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>CSS position relative question</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!--here, I have used div as a "parent" to apply some margin.-->
<div class="parent">
<div class="relative"></div>
</div>
</body>
</html>
I am confused why bottom:200px;
is not applied to box? In CSS, Isn't it true that the last defined rule is applied? so, in my code, I have defined bottom:200px;
in the last. shouldn't it overwrite top:100px;
like left:100px;
overwriting right:100px;
?
I know, the question seems confusing, but I have tried hard to explain it simply.but, if it is still not understandable, I am happy to try again. :)
From the Specification:
If neither 'left' nor 'right' is 'auto', the position is over-constrained, and one of them has to be ignored. If the 'direction' property of the containing block is 'ltr', the value of 'left' wins and 'right' becomes -'left'. If 'direction' of the containing block is 'rtl', 'right' wins and 'left' is ignored.
So it's not about the order of the CSS but the direction which is in most of the case ltr
so left will always win. Same logic for bottom
and top
if you continue reading the Specification.
If neither is 'auto', 'bottom' is ignored (i.e., the used value of 'bottom' will be minus the value of 'top').