内容超出页面视口时,如何设置右侧padding/margin?已尝试浮动等方案
Great question! Let's break down whether to use margin-right or padding-right for your scenario, plus a better alternative you might not have considered:
1. Using margin-right on #content
This adds empty space outside your gray content box. Since margins sit outside the element's background, this space will be blank (no gray color). When you scroll all the way to the right, you'll see this empty gap after the #content ends.
Note: This will make the overall scrollable area wider (your #content's 200em width plus the margin value). Here's how to implement it:
#content { width: 200em; height: 4em; background-color: #dcdcdc; margin-right: 2em; /* Adjust to your desired space */ }
2. Using padding-right on #content
This adds space inside your #content element—meaning the gray background will extend into this padding area. By default, padding adds to the element's total width (so your #content would become 200em + padding width). To keep the total width at 200em, add box-sizing: border-box to include padding in the specified width:
#content { width: 200em; height: 4em; background-color: #dcdcdc; padding-right: 2em; box-sizing: border-box; /* Padding is now part of the 200em width */ }
3. The Cleanest Solution: Add padding-right to the Body
Instead of modifying #content directly, adjust the body's right padding. This creates a consistent buffer between all content and the viewport edge, even when scrolling. It keeps your #content dimensions intact and avoids expanding the scrollable area unnecessarily:
body { margin: 0; padding: 3em 5em 3em 3em; /* 5em right padding for extra space */ height: 100%; overflow: auto; }
Why Floating Didn't Work
Floating elements are designed for layout tasks like wrapping text around an element—they don't affect the scrollable area's padding or margin. Floating #content wouldn't add the right-side space you're looking for because it doesn't modify the element's box model or the parent's spacing.
So to sum up:
- Use
margin-righton#contentif you want empty space after the gray box. - Use
padding-righton#content(withbox-sizing) if you want the gray background to extend into the space. - Use body
padding-rightfor the most consistent and clean solution.
内容的提问来源于stack exchange,提问作者Kaya Toast

