<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/imghw/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!