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

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

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; */
        }
相关推荐
云水一下1 天前
TypeScript 从零基础到精通(五):高级类型与泛型
前端·javascript·typescript
counterxing1 天前
vibe coding 之后,我更不想打字了
前端·agent·ai编程
copyer_xyf1 天前
Python 模块与包的导入导出
前端·后端·python
研☆香1 天前
es6新特性功能介绍(四)
前端·ecmascript·es6
微扬嘴角1 天前
React篇1--JSX语法规则、组件、组件实例的3大特性
前端·react.js·前端框架
copyer_xyf1 天前
Python venv 虚拟环境
前端·后端·python
无聊的老谢1 天前
Vue 3 + TypeScript 构建大型电信运维平台的前端架构设计
前端·vue.js·typescript
xiaofeichaichai1 天前
Map / Set / WeakMap / WeakSet
前端·javascript
李可以量化1 天前
成交量的终极量化策略:价量共振指标完整实现(下篇)
前端·数据库·人工智能
copyer_xyf1 天前
Python 如何同时做很多事:进程、线程、协程
前端·后端·python