Absolute Positioning Without Coordinates in CSS
In fact, specifying coordinates is not necessary for absolute positioning. If you simply write position
to an element in the value absolute
, it will become absolutely positioned, but will remain in the same place where it was. At the same time, all other elements will behave as if our element does not exist and can overlap it.
Let's look at some examples.
Example
To start, let's just make three blocks with no positioning and some text between them:
<div id="elem1"></div>
<div id="elem2"></div>
text text text text text text
<div id="elem3"></div>
#elem1 {
width: 200px;
height: 150px;
border: 1px solid red;
}
#elem2 {
width: 100px;
height: 100px;
margin-left: 10px;
border: 1px solid green;
}
#elem3 {
width: 50px;
height: 150px;
border: 1px solid blue;
}
:
Example
Now let's add absolute
to the green block. As a result, this block will stay in place, and all the elements below will behave as if our element is not there and will overlap it:
<div id="elem1"></div>
<div id="elem2"></div>
text text text text text text
<div id="elem3"></div>
#elem1 {
width: 200px;
height: 150px;
border: 1px solid red;
}
#elem2 {
position: absolute;
width: 100px;
height: 100px;
margin-left: 10px;
border: 1px solid green;
}
#elem3 {
width: 50px;
height: 150px;
border: 1px solid blue;
}
:
Example
Now let's add the left
property without adding a vertical position. As a result, horizontally our block will become at the specified value, and vertically it will remain where it was:
<div id="elem1"></div>
<div id="elem2"></div>
text text text text text text
<div id="elem3"></div>
#elem1 {
width: 200px;
height: 150px;
border: 1px solid red;
}
#elem2 {
position: absolute;
left: 40px; /* add horizontal position */
width: 100px;
height: 100px;
margin-left: 10px;
border: 1px solid green;
}
#elem3 {
width: 50px;
height: 150px;
border: 1px solid blue;
}
:
Example
Now let's, on the contrary, add the top
property without adding the horizontal position. As a result, our block will become vertically at the specified value, and horizontally - will remain standing where it was:
<div id="elem1"></div>
<div id="elem2"></div>
text text text text text text
<div id="elem3"></div>
#elem1 {
width: 200px;
height: 150px;
border: 1px solid red;
}
#elem2 {
position: absolute;
top: 100px; /* add vertical position */
width: 100px;
height: 100px;
margin-left: 10px;
border: 1px solid green;
}
#elem3 {
width: 50px;
height: 150px;
border: 1px solid blue;
}
: