css 实现居中

一、水平居中
  1. 文本居中:text-align: center;
  2. flex布局
    (1)容器:flex-direction: row; justify-content: center;, flex-direction: column; align-items: center;
    (2)项目:根据容器的主轴方向,选择 justify-self: center; 或者 align-self: center;
二、垂直居中
  1. 行内元素文本垂直居中:vertical-align: middle;
  2. 块级元素文本垂直居中:height: x; line-height: x;
  3. flex布局
    (1)容器:flex-direction: row; align-items: center;, flex-direction: column; justify-content: center;
    (2)项目:根据容器的主轴方向,选择 justify-self: center; 或者 align-self: center;
三、比较通用的方法设置居中
  1. 设置 position
    (1)相对浏览器:设置 positon: fixed
    (2)相对父元素:设置 position: absoluteposition: relative (父元素为 position: static 时选择后者)

  2. 设置 margin
    (1)预处理1:若是元素脱离了文本流(失去了 block 或者 inline-block 的流特性),需要进行预处理操作使得元素在需要对齐的方向上重新具有流特性。没有流特性的元素,无法使用 auto 来自动计算 margin

    /* 设置left, right属性可以让元素在水平方向上恢复流特性 */
    left: 0;
    right: 0;
    
    /* 设置top, bottom属性可以让元素在垂直方向上恢复流特性 */
    top: 0;
    bottom: 0;
    

    (2)预处理2:水平居中需要元素设置 width,垂直居中需要元素设置 height。这样才能通过 auto 为元素自动计算 margin

    (3)设置 margin: auto;(水平垂直对齐)、margin: 0 auto;(水平对齐)、margin: auto 0;(垂直对齐)

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值