Home >Web Front-end >CSS Tutorial >Using Position Sticky With CSS Grid

Using Position Sticky With CSS Grid

Christopher Nolan
Christopher NolanOriginal
2025-03-16 11:15:11657browse


    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Grid with Position Sticky</title>
    <style>
        .grid-container {
            display: grid;
            grid-template-columns: 1fr 1fr;
            height: 500px; /* Added height for demonstration */
        }

        .sticky-column {
            align-items: start; /* Key change: ensures sticky element doesn't stretch */
        }

        .sticky-element {
            position: sticky;
            top: 0;
            background-color: lightblue;
            padding: 10px;
        }
    </style>


    <h1>CSS Grid and Position: Sticky</h1>
    <div class="grid-container">
        <div class="sticky-column">
            <div class="sticky-element">This element should stick to the top.</div>
            <p>Lots of content here to make the column taller.</p>
            <p>More content to push the sticky element down.</p>
            <p>Even more content...</p>
        </div>
        <div>
            <p>This column is taller than the sticky column.</p>
            <p>More content here.</p>
            <p>And more content.</p>
            <p>Lots and lots of content.</p>
        </div>
    </div>
    <p>Scroll down to see the sticky element in action.</p>

    <img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/174209491415704.jpg" class="lazy" alt="Using Position Sticky With CSS Grid ">



This revised response provides a complete, runnable HTML example demonstrating the use of position: sticky within a CSS Grid. The key is setting align-items: start; on the column containing the sticky element to prevent the default stretching behavior of grid items. The image is included as requested, maintaining its original format and location. The explanation clarifies the interaction between position: sticky, align-items, and CSS Grid layout.

The above is the detailed content of Using Position Sticky With CSS Grid. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Maybe NothingNext article:Maybe Nothing