CSS居中总结

行内元素块级元素讨论

<div class="container">
     <div class="box1">1</div>
     <span class="box2">2</span>
</div>
水平居中

对于行内元素:text-align: center

.container {
    text-align: center;
}

对于块级元素:margin: auto;

.box1 {
    width: 5vw;
    height: 20vh;
    margin: auto;
    background-color: pink;
}

在这里插入图片描述

垂直居中
  1. 单行文字垂直居中 设置 line-height = height
    很常用,主要用于文字的排版

  2. 块级元素:display: flex

.container {
    width: 100vw;
    height: 50vh;
    display: flex;
    align-items: center; /*纵轴方向居中*/
    justify-content: center; /*横轴方向居中*/
    background-color: gray;
}

在这里插入图片描述

  1. 块级元素:绝对定位 + margin: auto;
.container {
    width: 100vw;
    height: 50vh;
    position: relative;
    background-color: gray;
}

.box1 {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 5vw;
    height: 20vh;
    background-color: pink;
}
  1. 块级元素:display: table-cell
.father {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.son {
    display: inline-block;
}
  1. 绝对定位(需要提前知道尺寸)
  2. 块级元素:绝对定位 + transform(不需要提前知道尺寸)
.container {
    position: relative;
    width: 100vw;
    height: 50vh;
    background-color: gray;
}

.box1 {
    width: 5vw;
    height: 20vh;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background-color: pink;
}
  1. grid布局
.wp {
    display: grid;
}
.box {
    align-self: center;
    justify-self: center;
}

PC端有兼容性要求,宽高固定,推荐absolute + 负margin
PC端有兼容要求,宽高不固定,推荐css-table
PC端无兼容性要求,推荐flex
移动端推荐使用flex

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值