简体   繁体   中英

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

In fact, I sometimes find that setting 50vw just brings the element around half of the distance it's supposed to be.

Why does this happen? What am I missing out here?

You need to subtract half the width of the item as well. You can do that, for example, with margin. There are other options as well such as calc.

See this fiddle with an example: 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM