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

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

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; */
        }
相关推荐
Java展博13 小时前
[前端够用就好] 跨域报错时,浏览器到底在拦谁
前端·状态模式
用户1129361121913 小时前
npm 都提示成功了,node_modules 为什么还占着 370M?
linux·前端·后端
掘金安东尼14 小时前
Agent Harness 也有 benchmark:评分榜与评测工作台现状
前端·agent
digger_41914 小时前
从零理解 Electron:主进程、渲染进程、preload 与 IPC 实战
前端·electron
去伪存真15 小时前
别让你的 RAG 平台“花五份钱、答一份结巴的题”:幂等性架构的自我修养
前端·agent
snow@li16 小时前
前端:导入EXCEL并解析文件内容,demo
前端·javascript·vue.js
补码缩写16 小时前
压缩PNG不损失透明:只量化RGB、alpha原样留的减色流程
前端
TDengine (老段)17 小时前
TDengine IDMP 知识库与知识图谱
大数据·前端·物联网·知识图谱·时序数据库·tdengine·涛思数据
goehou18 小时前
PNG 转 WebP 不一定变小,我量了三类图
前端·性能优化·webp·sharp
夕水19 小时前
一个小小的颜色选择器,差点让我开发出一个组件库来
前端·javascript·typescript