日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

css --- [小结]让盒子水平垂直居中的解决方案

發(fā)布時間:2023/12/10 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 css --- [小结]让盒子水平垂直居中的解决方案 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

描述

  • 有如下模型,想辦法讓
<style>.box{width: 500px;height: 500px;background: skyblue;} </style> <div class="box"><div class="inner"></div> </div>
  • 想辦法讓inner在box中水平垂直居中

方案1: 使用絕對定位

  • 讓子盒子相對于父盒子絕對定位,
  • 然后距離 左/上 邊50%,
  • 在將外邊距設為盒子 寬/高 的一半
    代碼如下:
.box{position: relative;width: 150px;height: 150px;background: skyblue; } .inner{position: absolute;width: 50px;height: 50px;left: 50%;top: 50%;margin-left: -25px;margin-top: -25px;background: lightcoral; }

方案2: 使用transform

  • 上面需要手動移動子盒子的寬高,即每次都要計算子盒子的寬高/2,
  • 可以嘗試使用CSS3的transform屬性,將盒子在水平和垂直方向移動-50%
  • 代碼如下:
.inner {position: absolute;width: 50px;height: 50px;left: 50%;top: 50%;transform: translate(-50%, -50%);background: lightcoral; }

方案3: margin…

  • 此方法比較奇怪…
  • 思路是利用絕對定位,讓盒子的left top right bottom全部為0,然后設置margin為auto
  • 代碼如下
.inner {position: absolute;width: 50px;height: 50px;left: 0;top: 0;right: 0;bottom: 0;margin: auto;background: lightcoral; }

方案4: 使用js

  • 使用js先獲取父盒子的 寬/高
  • 在獲取子盒子的寬高,然后使用絕對定位,將左邊距設置為 (父盒子寬 - 子盒子寬) / 2
<script>var box = document.querySelector('.box')var inner = document.querySelector('.inner')// 父盒子 寬高var bW = box.offsetWidthvar bH = box.offsetHeight// 子盒子 寬/高var iW = inner.offsetWidthvar iH = inner.offsetHeightinner.style.position = 'absolute'inner.style.left = (bW - iW) / 2 + 'px'inner.style.top = (bH - iH) / 2 + 'px' </script>

方案5: flex布局

  • 個人認為最簡單最棒的一種布局
  • 只需設置父元素的布局為flex布局,然后設置 justify-content和align-items屬性
  • 代碼如下:
<style> .box {display: flex;justify-content: center;align-items: center;width: 150px;height: 150px;background: skyblue; } .inner {width: 50px;height: 50px;background: lightcoral; } </style>

方案6: table-cell

  • 思想是將子盒子變成文本的形式(inline-block)
  • 然后向控制文本水平垂直居中
<style>.box {display: table-cell;text-align: center;vertical-align: middle;width: 150px;height: 150px;background: skyblue;}.inner {display: inline-block;width: 50px;height: 50px;background: lightcoral;} </style> 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎

總結(jié)

以上是生活随笔為你收集整理的css --- [小结]让盒子水平垂直居中的解决方案的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。