css实现水平居中、垂直居中、垂直水平居中布局

水平居中

1.只需要把行内元素包裹在一个属性display为block的父层元素中,并为父层元素添加如下属性即可:

.parent {
    text-align:center;
}

2.块状元素解决方案

.item {
    margin: 0 auto;
}

3.多个块状元素解决方案
将元素的display属性设置为inline-block,并且把父元素的text-align属性设置为center即可:

.parent {
    text-align:center;
}

4.多个块状元素解决方案 (使用flexbox布局实现)
使用flexbox布局,只需要把待处理的块状元素的父元素添加属性display:flex及justify-content:center即可:

.parent {
    display:flex;
    justify-content:center;
}

在子元素宽度总和在父元素宽度内,居中正常。如果子元素宽度总和大于父元素宽度,这个方法会将子元素全部强制进父元素的宽度,在设置了宽高150px的情况下:

垂直居中

1.单行的行内元素解决方案

.parent {
    background: #222;
    height: 200px;
}

/* 以下代码中,将a元素的height和line-height设置的和父元素一样高度即可实现垂直居中 */
a {
    height: 200px;
    line-height:200px; 
    color: #FFF;
}

2.多行的行内元素解决方案
组合使用display:table-cell和vertical-align:middle属性来定义需要居中的元素的父容器元素生成效果,如下:

.parent {
    background: #222;
    width: 300px;
    height: 300px;
    /* 以下属性垂直居中 */
    display: table-cell;
    vertical-align:middle;
}

3.已知高度的块状元素解决方案

.parent{
        /* 设置父级元素的定位为relative */
	position: relative;
}
.item{
    top: 50%;
    margin-top: -50px;  /* margin-top值为自身高度的一半 */
    position: absolute;
    padding:0;
}

垂直水平居中

1.已知高度和宽度的元素解决方案1

设置父元素属性  position:relative;,如下代码段:

.parent{
    position: relative;
}
.item{
    position: absolute;
    margin:auto;
    left:0;
    top:0;
    right:0;
    bottom:0;
}

2.已知高度和宽度的元素解决方案2

设置父元素属性  position:relative;

.item{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;  /* 设置margin-left / margin-top 为自身高度的一半 */
    margin-left: -50px;
}

3.未知高度和宽度元素解决方案

设置父元素属性  position:relative;

.item{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);  /* 使用css3的transform来实现 */
}

4.使用flex布局实现

.parent{
    display: flex;
    justify-content:center;
    align-items: center;
}

 原文链接:https://www.cnblogs.com/notepades/p/6178510.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值