发布时间:2024-01-24阅读(5)
马上又要到秋招的时候了,又有不少人打算换工作了。前端在面试中总会被问到的一道基础题div居中方法,这里给大家总结一下都有哪些常用的方法。
绝对定位还未偏移一半自身宽高
<style> .parent { position: relative; width: 500px; height: 500px; border: solid red 1px; } .demo { position: absolute; width: 100px; height: 100px; border: solid blue 1px; top: 50%; left: 50%; margin-top: -50px; margin-left: -50px; } </style> <body> <div > <div ></div> </div> </body>
通过flex弹性布局设置垂直居中和水平居中
<style> .parent { width: 500px; height: 500px; border: solid red 1px; display: flex; // 垂直,水平居中 align-items: center; justify-content: center; } .demo { width: 100px; height: 100px; border: solid blue 1px; } </style> <body> <div > <div ></div> </div> </body>
在子元素不知道自身宽高情况,使用transform进行比偏移。
<style> .parent { position: relative; width: 500px; height: 500px; border: solid red 1px; } .demo { position: absolute; border: solid blue 1px; top: 50%; left: 50%; transform: translate(-50%, -50%); } </style> <body> <div > <div >居中</div> </div> </body>
以上3种是常用的方法,当然还有其他居中方法比如grid布局,table-cell布局等。
欢迎分享转载→http://www.youqulife.com/read-218942.html
Copyright © 2024 有趣生活 All Rights Reserve吉ICP备19000289号-5 TXT地图HTML地图XML地图