CSS Properties
CSS scroll-margin-block Property
Photo Credit to CodeToFun
🙋 Introduction
The scroll-margin-block
property in CSS is used to adjust the scroll snap area at the block start and block end of an element.
This property is particularly useful when implementing scroll snapping in a vertical writing mode or when you need to add margins to the scroll snap position. By using this property, you can control the proximity of elements to the container's scroll position, enhancing the scrolling experience.
💡 Syntax
The syntax for the scroll-margin-block
property is straightforward and allows you to specify the margin for the block start and block end.
element {
scroll-margin-block: start end;
}
Here, start and end can be any valid CSS length value (e.g., px, em, rem) or a percentage.
🎛️ Default Value
The default value of the scroll-margin-block
property is 0, meaning no additional margin is added to the scroll snap area.
🏠 Property Values
Value | Description |
---|---|
length | Specifies a fixed margin (e.g., 10px, 2em, 1rem). |
percentage | Specifies a margin relative to the block size of the element (e.g., 10%). |
📄 Example
In this example, we'll add scroll margin to a section element to ensure it doesn't touch the edges when snapped into view.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS scroll-margin-block Example</title>
<style>
html {
scroll-snap-type: y mandatory;
}
section {
height: 100vh;
scroll-snap-align: start;
scroll-margin-block: 20px;
background: lightblue;
border: 2px solid blue;
margin: 10px 0;
}
</style>
</head>
<body>
<h1>Sections with Custom Scroll Margin Block</h1>
<section>Section 1</section>
<section>Section 2</section>
<section>Section 3</section>
</body>
</html>
🖥️ Browser Compatibility
The scroll-margin-block
property is supported in most modern browsers, including the latest versions of Chrome, Firefox, Safari, Edge, and Opera. However, it is always a good practice to test your website across different browsers to ensure compatibility.
🎉 Conclusion
The scroll-margin-block
property is a useful tool for web developers looking to fine-tune the scrolling experience on their websites.
By adding margins to the scroll snap area, you can ensure a more comfortable and visually appealing layout. Experiment with different values to see how this property can improve the usability of your scrollable content.
👨💻 Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (CSS scroll-margin-block Property), please comment here. I will help you immediately.