CSS 元素居中的各种方式

CSS 元素居中的各种方式

水平居中

内联元素

  • 外层添加一个块级父元素,并设置 text-align: center;
 <div style="text-align: center;">
   <a> 内联元素 </a>
 </div>

块级元素

  • 设置 margin: 0 auto; 以及宽度
 <div style="margin: 0 auto; width: 200px;">
   块级元素
 </div>

多个块级元素

  1. 方法一 内联
  • 外层添加一个块级父元素,并设置 text-align: center;
  • 子元素设置成内联元素
  1. 方法二 flexbox
  • 外层添加一个块级父元素,并设置
  • display: flex; justify-content: center;

relative + absolute

  • 父元素 postion: relative;
  • 子元素 宽度+偏移量+外边距
  • width: 500px; left: 50%; margin-left: -250px;

垂直居中

内联元素

  1. 方法一 内边距
  • 设置 padding: 50px;
  1. 方法二 元素高度=行高
  • 设置 height:100px; line-height:100px;
  1. 方法三 flexbox(父元素要设置高度)
  • 设置 height:200px; display:flex; flex-direction: column; justify-content: center;

块级元素

宽度、高度固定 width: 18em; height: 10em;

  1. 方法一
  • 父元素设置 position:relative;
  • 子元素设置 top和left 为 50%; margin上为一半高 margin左为一半宽
    position:absolute; top: 50%; left: 50%; margin-left: -9rem; margin-top: -5rem;
  1. 方法二
  • 父元素设置 position:relative;
  • 子元素设置 top 为 calc(50% 剪 一半高) left 为 calc(50% 剪 一半宽)
    position:absolute; top: calc(50% - 5em); left: calc(50% - 9em);

宽度、高度不固定

  • 父元素设置 position:relative;
  • 子元素设置 top和left 为 50%; transform: translate(-50%, -50%);
    position:absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);

flexbox

  1. 方法一 margin
  • 父元素设置 display: flex;
  • 子元素设置 宽度 + margin: auto;
  1. 方法二
  • 父元素设置 display: flex;
  • 子元素设置 宽度 + justify-content: center; align-items: center;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值