Positioning elements in CSS allows you to control where an element appears on the page. By using different positioning techniques, you can precisely place elements in relation to other elements, the page itself, or the viewport. Here's a explain about types of positioning:
By default, elements are positioned static. This means they flow in the normal document layout.
<h1>Welcome to Codersmile!</h1>
<p>Our mission is to make coding fun and accessible to everyone.</p>
In this example, the <h1>
and <p>
elements are statically positioned. They appear in the order they are written in the HTML.
When an element is positioned relative, it is moved relative to its original position without affecting the layout of other elements.
<h1 style="position: relative; top: 10px; left: 20px;">Welcome to Codersmile!</h1>
<p>Our mission is to make coding fun and accessible to everyone.</p>
Here, the <h1>
is moved 10 pixels down and 20 pixels to the right from its original position.
An element with absolute positioning is placed exactly where you want it relative to its nearest positioned ancestor (anything other than static
). If there is no such ancestor, it will be positioned relative to the initial containing block (usually the viewport).
<div style="position: relative;">
<h1 style="position: absolute; top: 0; right: 0;">Welcome to Codersmile!</h1>
</div>
<p>Our mission is to make coding fun and accessible to everyone.</p>
In this example, the <h1>
is positioned at the top right corner of the <div>
because the <div>
has position: relative
.
With fixed positioning, an element is positioned relative to the viewport, which means it stays in the same place even when the page is scrolled.
<h1 style="position: fixed; top: 0; width: 100%;">Welcome to Codersmile!</h1>
<p>Our mission is to make coding fun and accessible to everyone.</p>
The <h1>
will remain at the top of the viewport no matter how much you scroll.
An element with sticky positioning behaves like relative
until it reaches a specified point (like scrolling down to a certain point), after which it behaves like fixed
.
<h1 style="position: -webkit-sticky; position: sticky; top: 0;">Welcome to Codersmile!</h1>
<p>Our mission is to make coding fun and accessible to everyone.</p>
The <h1>
will act like relative
until you scroll past it. Once it reaches the top of the viewport, it will stick there like fixed
.