多种方式垂直水平居中

南笙酒味 提交于 2020-02-03 00:11:28

1. 不需要知道父容器和子容器的具体尺寸

 (1)方法一:margin

 <div class="wrapper">
        <div class="content"></div>
    </div>

 

.wrapper {
    display: table-cell;
    width: 500px;
    height: 500px;
    text-align: center; /*水平居中*/
    border: 1px solid #eee;
    vertical-align: middle; /*图片垂直居中*/
    position: relative;
    
} 
.content {
    width: 200px;
    height: 200px;
    background-color: red;
    margin: auto;
}

 

   (2)方法二:绝对定位 + transform, 应用到了css3知识,需要注意兼容性问题

<div class="wrapper">
        <div class="content"></div>
    </div>

 

.wrapper {
    display: block;
    width: 500px;
    height: 500px;
    border: 1px solid #eee;
    position: relative;
    
} 
.content {
    width: 200px;
    height: 200px;
    background-color: red;
    position: absolute;
    left: 50%;
    right: 50%;
   transform: translate(-50%, -50%);
}

 

  (3)flex弹性盒子,应用到了css3知识,需要注意兼容性问题

<div class="wrapper">
        <div class="content"></div>
    </div>

 

 

.wrapper {
    width: 500px;
    height: 500px;
    border: 1px solid #eee;
    display:flex;
    justify-content:center;// 主轴(一般为横轴)的排列方式
    align-items: center;  // 纵轴(一般为竖轴)的排列方式
} 
.content {
    width: 200px;
    height: 200px;
    background-color: red;
}

 


 

2.已知宽高尺寸

<div class="wrapper">
        <div class="content"></div>
    </div>

 

.wrapper {
    width: 500px;
    height: 500px;
    border: 1px solid #eee;
    position: relative;
} 
.content {
    width: 200px;
    height: 200px;
    background-color: red;
    position: absolute;
    left: 50%;
    top: 50%;
    /*自身宽高一半的负值*/
    margin-left: -100px;
    margin-top: -100px;
}

3.文字水平垂直居中

  (1)单行文字

  水平居中在父级元素添加text-align: center;

  垂直居中在父级元素添加和父级元素高度一样的line-height

  (2)多行文字

  水平居中在父级元素添加text-align: center;

  垂直居中在父级元素添加一定的行高和padding设置为xx 0;

  

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!