居中一个元素(水平+垂直居中)

我们的示例代码全在此基础上修改:

html 复制代码
......
<style>
  *     {
            margin: 0;
            padding: 0;
        }

        .par {
            width: 600px;
            height: 400px;
            background-color: antiquewhite;

            display: flex;
            justify-content: center;
            align-items: center;
        }

        .chi1 {
            width: 60px;
            height: 40px;
            background-color: rgb(211, 205, 197);
        }
    </style>
............
<div class="par">
        <div class="chi1">1</div>
    </div>

1.flex 弹性布局居中

具体原理参考下面这篇博客:

flex 弹性布局_本郡主是喵的博客-CSDN博客

css 复制代码
 .par {
 ....
            display: flex;
            justify-content: center;
            align-items: center;
        }

2.垂直 + 水平居中内容

对于内容是行内式元素(内容大小撑起标签宽高)或文字,是有效的。

line-heignt == height ,能使文字垂直对齐,text-align:center,能使内容居中水平对齐

css 复制代码
  .chi1 {
         
.........
            text-align: center;
            line-height: 40px;
        }

3. 采用绝对布局

父元素,采用相对布局,子元素采用相对布局。

我们利用方位属性,调至子元素相对于父元素的方位,达到居中的效果。

PS: top 和bottom,right 和left属性都是相对的,调整一个,另外一个都会失效。

css 复制代码
          .par {
......           
         position: relative;
        }

        .chi1 {
 .......
            position: absolute;
            top: 45%;
            left: 45%;
            /* bottom: 0;
            right: 0; */
        }
相关推荐
arvin_xiaoting2 小时前
OpenClaw学习总结_I_核心架构_8:SessionPruning详解
前端·chrome·学习·系统架构·ai agent·openclaw·sessionpruning
工程师老罗3 小时前
Image(图像)的用法
java·前端·javascript
swipe4 小时前
把 JavaScript 原型讲透:从 `[[Prototype]]`、`prototype` 到 `constructor` 的完整心智模型
前端·javascript·面试
问道飞鱼4 小时前
【前端知识】React 组件生命周期:从底层原理到实践场景
前端·react.js·前端框架·生命周期
CHU7290355 小时前
定制专属美丽时刻:美容预约商城小程序的贴心设计
前端·小程序
浩~~5 小时前
反射型XSS注入
前端·xss
AwesomeDevin5 小时前
AI时代,我们的任务不应沉溺于与 AI 聊天,🤔 从“对话式编程”迈向“数字软件工厂”
前端·后端·架构
harrain6 小时前
antvG2折线图和区间range标记同时绘制
前端·javascript·vue.js·antv·g2
德育处主任Pro6 小时前
从重复搭建到高效生产,RollCode的H5开发新范式
前端
蜡台6 小时前
SPA(Single Page Application) Web 应用(即单页应用)架构模式 更新
前端·架构·vue·react·spa·spa更新