您的位置:首页 > 其它

多种方式垂直水平居中

2016-09-08 19:47 393 查看
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;

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: