CSS居中对齐 (水平垂直居中对齐)

方案一:flex布局【推荐】

给容器添加样式

复制代码
display: flex;
justify-content: center;
align-items: center;
html 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        display: flex;
        justify-content: center;
        align-items: center;
        border: 1px solid gray;
        width: 200px;
        height: 100px;

      }

      .item {
        width: 50px;
        height: 50px;
        background-color: yellow;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <span class="item">水平垂直居中</span>
    </div>
  </body>
</html>

方案二:子绝父相 + transform (CSS3)

限制条件:浏览器需支持CSS3,比较老的浏览器不适用

给容器(父元素)添加样式

html 复制代码
position: relative

给内部元素添加样式

html 复制代码
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

方案三:子绝父相 + 自动外边距(指定高度和宽度)

给容器(父元素)添加样式

复制代码
position: relative

给内部元素添加样式

复制代码
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;

方案四:子绝父相 + 负外边距 (知道宽度和高度 + 宽度和高度计算)不推荐

限制条件 :需知道内部元素的宽度和高度

给容器(父元素)添加样式

复制代码
position: relative

给内部元素添加样式

复制代码
position: absolute;
left:50%;
margin-left:-内部元素宽度的一半;
top: 50%;
margin-top: -内部元素高度的一半;
html 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        margin: 30px 30px 0px 300px;
        border: 1px solid gray;
        height: 100px;
        position: relative;
      }
      .item {
        background-color: yellow;
        position: absolute;
        left: 50%;
        margin-left: -150px;
        top: 50%;
        margin-top: -25px;
        width: 300px;
        height: 50px;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <span class="item">水平垂直居中 -- 子绝父相 + 负外边距</span>
    </div>
  </body>
</html>
相关推荐
Cobyte4 分钟前
AI全栈实战:使用 Python+LangChain+Vue3 构建一个 LLM 聊天应用
前端·后端·aigc
NEXT0617 分钟前
前端算法:从 O(n²) 到 O(n),列表转树的极致优化
前端·数据结构·算法
剪刀石头布啊23 分钟前
生成随机数,Math.random的使用
前端
剪刀石头布啊23 分钟前
css外边距重叠问题
前端
剪刀石头布啊24 分钟前
chrome单页签内存分配上限问题,怎么解决
前端
剪刀石头布啊26 分钟前
css实现一个宽高固定百分比的布局的一个方式
前端
剪刀石头布啊29 分钟前
js数组之快速组、慢数组、密集数组、稀松数组
前端
mango_mangojuice1 小时前
Linux学习笔记(make/Makefile)1.23
java·linux·前端·笔记·学习
Days20501 小时前
简单处理接口返回400条数据本地数据分页加载
前端
Novlan11 小时前
@tdesign/uniapp 图标瘦身
前端