tft每日頭條

 > 職場

 > css設置div居中的關鍵代碼

css設置div居中的關鍵代碼

職場 更新时间:2024-08-02 02:22:00

馬上又要到秋招的時候了,又有不少人打算換工作了。前端在面試中總會被問到的一道基礎題div居中方法,這裡給大家總結一下都有哪些常用的方法。

絕對定位
  • 父級元素(parent)采用相對定位(relative),需要居中的元素(demo)采用絕對定位(absolute)。
  • 居中元素向上偏移50%,向左偏移50%,此時左頂點位于中心,不過我們需要的是整體居中,所以在偏移自身一半的寬高。(如下圖)

css設置div居中的關鍵代碼(css篇前端面試中常問的div居中方法)1

還未偏移一半自身寬高

<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 class="parent"> <div class="demo"></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 class="parent"> <div class="demo"></div> </div> </body>

使用transform居中

在子元素不知道自身寬高情況,使用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 class="parent"> <div class="demo">居中</div> </div> </body>

以上3種是常用的方法,當然還有其他居中方法比如grid布局,table-cell布局等。

,

更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!

查看全部

相关職場资讯推荐

热门職場资讯推荐

网友关注

Copyright 2023-2024 - www.tftnews.com All Rights Reserved