簡體   English   中英

為什么在具有絕對/固定位置的元素上設置 50vw 或 50% 沒有將其准確設置在中間?

[英]Why does setting 50vw or 50% on an element with position absolute/fixed not set it exactly in the middle?

事實上,我有時會發現設置50vw只會使元素達到預期距離的一半左右。

為什么會發生這種情況? 我在這里錯過了什么?

您還需要減去項目寬度的一半。 例如,您可以使用邊距來做到這一點。 還有其他選項,例如 calc。

用一個例子看這個小提琴: https : //jsfiddle.net/cgsymvyg/1/

 #box1 { border: 1px solid red; background: green; color: white; width: 100px; height: 100px; position: absolute; left: 50vw; } #box2 { top: 200px; border: 1px solid green; background: red; color: white; width: 100px; height: 100px; position: absolute; left: 50vw; margin-left: -50px; } #box3 { top: 400px; border: 1px solid yellow; background: blue; color: white; width: 100px; height: 100px; position: absolute; left: calc(50vw - 50px); }
 <div id="box1"> Box 1 </div> <div id="box2"> Box 2 </div> <div id="box3"> Box 3 </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM