css 布局(垂直居中,水平居中)

實(shí)現(xiàn)垂直居中布局

1.已知寬高

/* 1 */
.container{
  width: 300px;
  height: 300px;
  background: yellowgreen;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -150px;
  margin-top: -150px;
}
/* 2 */
.container{
  width: 300px;
  height: 300px;
  background: yellowgreen;
  position: absolute;
  top: calc(50% - 150px);
  left: calc(50% - 150px);
}

2.未知寬高

/* 1 */
.container{
  background: yellowgreen;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
/* 2 position + auto*/
.container{
  background: yellowgreen;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}
/* 3 flex+ auto */
.wrapper {
  width: 100%;
  height: 100vh;
  display: flex;
}
.wrapper .content {
  margin: auto;
}
/* 4. 父元素居中*/
.wrapper {
   display: flex;
   /* 盒子橫軸的對(duì)齊方式 */
   justify-content: center;
   /* 盒子縱軸的對(duì)齊方式 */
   align-items: center;
}
/* 5.body內(nèi)部居中*/
.content {
   /* 1vh = 1% * 視口高度 */
   margin: 50vh auto;
   transform: translateY(-50%);
}

css 盒子模型(默認(rèn)為content-box)

CSS盒模型本質(zhì)上是一個(gè)盒子,封裝周圍的HTML元素,它包括:邊距,邊框,填充,和實(shí)際內(nèi)容。


image.png
  • 標(biāo)準(zhǔn)盒子模型:width = content
  • IE盒子模型:width = content + pading + border

  • 設(shè)置標(biāo)準(zhǔn)盒子模型:box-sizing : content-box
  • 設(shè)置IE盒子模型:box-sizing : border-box
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容