DEV Community

Cover image for POSITIONING IN CSS
Vinoth Kumar
Vinoth Kumar

Posted on

POSITIONING IN CSS

ABSOULTE POSITIONING:
Removes the element from the document flow and places it relative to the nearest ancestor with a positioning context,eg: relative, absolute, or fixed.

EXAMPLE:

<html>
<head>
    <style>
        .fixed {
            position: fixed;
            top: 10px;
            right: 10px;
            background-color: lightgreen;
            padding: 20px;
            border: 2px solid black;
        }
        .content {
            height: 1200px;
            padding: 10px;
        }
    </style>
</head>
<body>
    <h2>Fixed Positioning Example</h2>
    <div class="fixed">Fixed Box</div>
    <div class="content">
        <p>Scroll down to see that the fixed box stays in place.</p>
        <p>This content simulates a long page.</p>
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

FIXED POSITIONING:
Removes the element from the flow and positions it relative to the viewport. It remains in place even when the page scrolls.

EXAMPLE:

<html>
<head>
    <style>
        .fixed {
            position: fixed;
            top: 10px;
            right: 10px;
            background-color: lightgreen;
            padding: 20px;
            border: 2px solid black;
        }
        .content {
            height: 1200px;
            padding: 10px;
        }
    </style>
</head>
<body>
    <h2>Fixed Positioning Example</h2>
    <div class="fixed">Fixed Box</div>
    <div class="content">
        <p>Scroll down to see that the fixed box stays in place.</p>
        <p>This content simulates a long page.</p>
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

STICKY POSITIONING:
Switches between relative and fixed based on the scroll position.

EXAMPLE:

<html>
<head>
    <style>
        .sticky {
            position: sticky;
            top: 0;
            background-color: yellow;
            padding: 10px;
        }
    </style>
</head>
<body>
    <div class="sticky">I am sticky</div>
    <p>Scroll down to see the effect.</p>
    <div style="height: 1000px;"></div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)