發布時間:2024-01-24閱讀(18)
馬上又要到秋招的時候了,又有不少人打算換工作了。前端在面試中總會被問到的一道基礎題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布局等。
Copyright ? 2024 有趣生活 All Rights Reserve吉ICP備19000289號-5 TXT地圖HTML地圖XML地圖