父容器宽度由JS设置时,为子元素添加固定右侧外边距的实现方案
left-container Without Modifying Their Base Styles Hey there! I get what you're trying to do—replicating that clean multi-block margin layout from The New Yorker, while keeping your reusable child elements untouched. Let's break down the solution:
Why Your Previous Attempts Didn't Work
Changing padding-right or margin-right on left-container only affects the container itself, not its child elements. Those properties don't inherit down to the kids, so you need a way to target just the children inside left-container without messing up their styles elsewhere.
Solution: Target Direct Children with CSS Subselectors
Use the direct child selector (>) to apply the right margin only to elements that are direct children of left-container. This way, the same child elements used elsewhere won't pick up this style.
Here's the CSS you can add:
/* Add fixed right margin to all direct children of left-container */ .left-container > * { margin-right: 32px; /* Replace with your desired fixed pixel value */ } /* Optional: Remove margin from the last child to avoid extra space at the end */ .left-container > *:last-child { margin-right: 0; }
How This Works
- The
>selector ensures we only target elements directly nested insideleft-container—no deeper descendants, no elements used in other parts of your site. - Since you're not modifying the child elements' base styles, they'll behave normally when used outside
left-container. - This plays nicely with your JavaScript-controlled
container-spice—the JS manages the container's width and margins, while this CSS handles the internal spacing ofleft-container's children.
If you're going for a grid-like layout (similar to The New Yorker's multi-column blocks), you could also use Flexbox or Grid on left-container with gap for consistent spacing, but the direct child margin approach is straightforward for a fixed right margin per element.
内容的提问来源于stack exchange,提问作者xiaolingxiao

