css居中布局总结:水平居中,垂直居中,水平垂直居中

1.   水平居中

1.1 被设置元素为行内元素,设置父元素:

.parent {
    text-aligen: center;
}

1.2 被设置元素为块状元素

/* 元素定宽时 */
.item {
    margin: 0 auto;
}

1.3 fit-content + margin

.parent {
  width: fit-content;
  margin: auto;
}

1.4 通过flex布局

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

2.垂直居中

2.1 line-height + height

前提是:父元素高度确定

/* 单行文本的竖直居中的方法是通过设置父元素的 height 和 line-height 高度一致来实现的*/
.parent {
    height: 100px;
    line-height: 100px;
}
/* 同时对元素要使其垂直居中,可设置其display: inline-block */
.parent {
  line-height: 100px;
  height: 100px;
}

.item {
  line-height: initial; /* 重置 */
  vertical-align: middle;
  display: inline-block;
}

2.2 vertical-align

vertical-align 用来指定行内元素(inline)或表格单元格(table-cell)元素的垂直对齐方

 

2.3 .flex布局

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

3.水平垂直居中

3.1 flex实现

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

3.2 grid布局实现

.parent {
  display: grid;
}

.item {
  justify-self: center; /* 水平居中 */
  align-self: center; /* 垂直居中 */
}

3.3 绝对定位+tranform

.parent {
  position: relative;
}

.child {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%); /* translate移动的时候,以元素本身的宽高为准 */
}

以下3种方法都需要被设置元素宽高固定,且设置父元素相对定位

3.4 绝对定位 + calc

前提时,元素的宽高要固定

.parent {
  position: relative;
}

.child {
   width: 100px;
   height: 100px;
   position: absolute;
   left: calc(50% - 50px); /* 元素本身宽100px */
   top: calc(50% - 50px); /* 元素本身高100px */
}

3.5 绝对定位 + 负margin

.parent {
  position: relative;
}

.child {
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -50px; /* 元素本身宽100px */
  margin-top: -50px; /* 元素本身高100px */
}

3. 6 绝对定位 + margin: auto

.parent {
  position: relative;
}

.child {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值