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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

css中如何实现上下居中效果

發布時間:2023/12/19 综合教程 39 生活家
生活随笔 收集整理的這篇文章主要介紹了 css中如何实现上下居中效果 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

這篇文章將為大家詳細講解有關css中如何實現上下居中效果,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

  單行的行內元素

  只需要設置單行行內元素的"行高等于盒子的高"即可;

  <style>

  #father{

  width:500px;

  height:300px;

  background-color:skyblue;

  }

  #son{

  background-color:green;

  height:300px;

  }

  </style>

  <divid="father">

  <spanid="son">我是單行的行內元素</span>

  </div>

  效果:

  1556519521438598.jpg

  多行的行內元素

  使用給父元素設置display:table-cell;和vertical-align:middle;即可;

  <style>

  #father{

  width:500px;

  height:300px;

  background-color:skyblue;

  display:table-cell;

  vertical-align:middle;

  }

  #son{

  background-color:green;

  }

  </style>

  <divid="father">

  <spanid="son">我是多行的行內元素我是多行的行內元素我是多行的行內元素我是多行的行內元素我是多行的行內元素我是多行的行內元素我是多行的行內元素我是多行的行內元素</span>

  </div>

  效果:

  1556519558892168.jpg

  塊級元素

  方案一:使用定位

  首先設置父元素為相對定位,再設置子元素為絕對定位,設置子元素的top:50%,即讓子元素的左上角垂直居中;

  定高度:設置絕對子元素的margin-top:-元素高度的一半px;或者設置transform:translateY(-50%);

  <style>

  #father{

  width:500px;

  height:300px;

  background-color:skyblue;

  position:relative;

  }

  #son{

  height:100px;

  background-color:green;

  position:absolute;

  top:50%;

  margin-top:-50px;

  }

  </style>

  <divid="father">

  <divid="son">我是塊級元素</div>

  </div>

  不定高度:利用css3新增屬性transform:translateY(-50%);

  <style>

  #father{

  width:500px;

  height:300px;

  background-color:skyblue;

  position:relative;

  }

  #son{

  width:100px;

  background-color:green;

  position:absolute;

  left:50%;

  transform:translateY(-50%);

  }

  </style>

  <divid="father">

  <divid="son">我是塊級元素</div>

  </div>

  效果:

  1556519576485117.jpg

  方案二:使用flexbox布局實現(高度定不定都可以)

  使用flexbox布局,只需要給待處理的塊狀元素的父元素添加屬性display:flex;align-items:center;

  <style>

  #father{

  width:500px;

  height:300px;

  background-color:skyblue;

  display:flex;

  align-items:center;

  }

  #son{

  width:100px;

  height:100px;

  background-color:green;

  }

  </style>

  <divid="father">

  <divid="son">我是塊級元素</div>

  </div>

總結

以上是生活随笔為你收集整理的css中如何实现上下居中效果的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。