You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

父容器宽度由JS设置时,为子元素添加固定右侧外边距的实现方案

Fixing Right Margin for Child Elements in 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 inside left-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 of left-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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:45:50