父 <div> 內有多個垂直分布的子 <div>(中間用 <br> 隔開),需讓子元素靠右對齊,並可預留右側間距。
float: right(經典、兼容性好)<div style="height: 300px; width: 300px; background: yellow; padding-right: 10px;">
<div style="height: 100px; width: 60%; background: blue; float: right;"></div>
<br>
<div style="height: 100px; width: 60%; background: black; float: right;"></div>
</div>
overflow: hidden 或 clearfix 清除浮動防塌陷。<div style="display: flex; flex-direction: column; align-items: flex-end; padding-right: 10px; height: 300px; background: yellow;">
<div style="height: 100px; width: 60%; background: blue;"></div>
<div style="height: 100px; width: 60%; background: black;"></div>
</div>
align-items: flex-end 直接實現右對齊,gap 替代 <br> 控制間距。<div style="display: grid; justify-items: end; padding-right: 10px; grid-template-rows: auto auto; background: yellow;">
<div style="height: 100px; width: 60%; background: blue;"></div>
<div style="height: 100px; width: 60%; background: black;"></div>
</div>
text-align: right + inline-block<div style="text-align: right; padding-right: 10px; background: yellow;">
<div style="display: inline-block; height: 100px; width: 60%; background: blue;"></div>
<br>
<div style="display: inline-block; height: 100px; width: 60%; background: black;"></div>
</div>
text-align 控制。無論哪種方案,在父容器設定 padding-right: 10px(或所需值)即可,子元素自動縮留空間。
| 場景 | 推薦方案 |
|---|---|
| 需兼容 IE9 及以下 | float: right + clearfix |
| 現代項目、移動端優先 | Flexbox (align-items: flex-end) |
| 複雜二維網格對齊 | Grid (justify-items: end) |
| 簡單行內元素右對齊 | text-align: right + inline-block |
Flexbox 以最少代碼解決最多對齊問題,建議作為首選方案。