如何在浏览器宽度调整时自动重新计算元素margin值
Hey there! The problem you're hitting is that using a fixed margin-left: 45.3% ties the short sentence's position to the parent container's width, not the actual length of the long sentence. When the browser resizes, the parent's width changes, but the fixed percentage doesn't adjust to match the long sentence's dynamic width—hence the misalignment.
Here are a few clean, reliable solutions to fix this:
方案1:用Flexbox实现自动右对齐(最推荐)
Flexbox is perfect for this kind of dynamic alignment. By setting the parent container (#first) to use flex layout and align items to the right, both sentences will automatically stick to the right edge, no matter how the browser resizes.
Update your CSS like this:
* { margin: 0; padding: 0; box-sizing: border-box; } html,body { height: 100%; font-size: 1rem; } #container { display: flex; width: 100%; } #first { border: 1px solid black; border-radius: 5px; width: 35%; height: 90vh; margin-left: 10px; display: flex; /* 启用flex布局 */ flex-direction: column; /* 子元素垂直排列 */ align-items: flex-end; /* 让所有子元素靠右对齐 */ } /* 移除#sentence1的margin-left设置 */ #second { border: 1px solid black; border-radius: 5px; height: 90vh; width: 50%; margin-left: 10px; }
This works because align-items: flex-end tells flex children to align to the right side of the parent container. Both sentences will always line up perfectly on their right edges, even when the window is resized.
方案2:用文本右对齐快速解决
If you don't need the flexibility of flexbox, a simpler approach is to set text-align: right on the parent container. This makes all text inside #first align to the right, which achieves the same alignment effect.
Modify the #first CSS:
#first { border: 1px solid black; border-radius: 5px; width: 35%; height: 90vh; margin-left: 10px; text-align: right; /* 文本右对齐 */ } /* 移除#sentence1的margin-left */
This is a lightweight solution that's great if you only need to align text, not more complex elements.
为什么固定百分比margin不行?
Your original margin-left: 45.3% is calculated based on the width of #first (the parent). When the browser resizes, #first's width changes, so 45.3% of that new width won't match the exact space needed to align the short sentence with the long one's right edge. The long sentence's width also changes as the text wraps or the container shrinks, making the fixed percentage even less reliable.
内容的提问来源于stack exchange,提问作者Maxxx




