当前位置:Gxlcms > css > css实现水平居中/垂直居中的一些方法

css实现水平居中/垂直居中的一些方法

时间:2021-07-01 10:21:17 帮助过:13人阅读

本文整理一些利用css实现水平居中/垂直居中的一些方法,教程都很基础,希望对大家有帮助!

一、水平居中

1. text-align:center(行内元素)

  给其父元素设置属性 text-align:center;

2. margin: 0 auto(块级元素)

  给元素本身设置 margin: 0 auto;

3. 元素的宽度固定

  1⃣️ position+margin-left

  1. .ele{
  2. position:absolute;
  3. width:固定;
  4. left:50%;
  5. margin-left:-0.5宽度;
  6. }

  2⃣️ position+left:0;right:0;margin:0 auto

  1. .ele{
  2. position:absolute;
  3. width:固定;
  4. left:0;
  5. right:0;
  6. margin:0 auto;
  7. }

4.元素的宽度不固定

  1⃣️css3-transform

  1. .ele{
  2. position:absolute;
  3. left:50%;
  4. transform:translate(-50%,0);
  5. }

  2⃣️css3-width:fit-content(当需要居中的元素设置了float:left时,可以给该元素的父元素设置如下属性)

  1. <span style="color: #000000">.ele-parent{
  2. width: -moz-fit-content;
  3. width: -webkit-fit-content;
  4. width:fit-content;
  5. margin:0 auto;
  6. }<br>该属性目前只支持Chrome 和 Firefox浏览器.</span>

  3⃣️flex

  1. .ele-parent{
  2. display: flex;
  3. justify-content: center;
  4. }

二、垂直居中

1. line-height:eleparent-height

  单行文本的垂直居中可以设置属性 line-height:父元素height

2. 元素的高度固定

  1⃣️position+margin-top

  1. .ele-parent{
  2. position:relative;
  3. }
  4. .ele{
  5. position:absolute;
  6. top:50%;
  7. height:固定;
  8. margin-top:-0.5高度;
  9. }

  2⃣️ position+top:0;bottom:0;margin:auto 0

  1. .ele{
  2. position:absolute;
  3. height:固定;
  4. top:0;
  5. bottom:0;
  6. margin:auto 0;
  7. }

3.元素高度不固定

  1⃣️vertical-align

  1. <span style="color: #000000">.ele-parent{
  2. display:table;
  3. }
  4. .ele{
  5. display:table-cell;<br>  vertical-align:middle;
  6. }</span><strong><span style="font-size: 16px">    </span></strong>

  2⃣️css3-transform

  1. .ele{
  2. position:absolute;
  3. top:50%;
  4. transform: translate(0,-50%);
  5. }

  3⃣️flex

  1. .ele-parent{
  2. display: flex;
  3. align-items:center;
  4. }

  

暂时只整理到这些,不足之处还请 批评指正!!!

  

以上就是css实现水平居中/垂直居中的一些方法的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行