CSS Positioning
CSS positioning controls where elements are placed on a page. With it, you can override the normal document flow.
The CSS position Property
The position property sets the positioning type of an element. It can take these values:
static— the default. The element follows the normal document flow.relative— the element is placed relative to its normal position.fixed— the element is placed relative to the viewport.absolute— the element is placed relative to the nearest positioned ancestor.sticky— the element switches between relative and fixed depending on the scroll position.
Elements are then moved to their final spot with the top, bottom, left, and right properties.
CSS position: static
All HTML elements are static by default. A static element is not affected by the top, bottom, left, and right properties and always follows the normal flow of the page.
Example
The div uses position: static and stays in the normal flow.
<style> block, give a div.static class position static and a 3px solid green border. Add a div using it. A static element follows the normal page flow.
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
div.static {
position: static;
border: 3px solid #73AD21;
}
</style>
</head>
<body>
<div class="static">This div has position: static. It follows the normal flow of the page.</div>
</body>
</html>
CSS position: relative
A relative element is placed relative to its normal position. Setting top, right, bottom, or left moves it away from that spot. The gap it leaves behind is not filled by other content.
Example
The div is shifted 30px to the right of its normal position.
<style> block, give a div.relative class position relative, left 30px, and a 3px solid green border. Add a div using it. It shifts 30px right of its normal position.
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
div.relative {
position: relative;
left: 30px;
border: 3px solid #73AD21;
}
</style>
</head>
<body>
<div class="relative">This div has position: relative and is moved 30px to the right of its normal position.</div>
</body>
</html>