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

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

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; */
        }
相关推荐
一只码代码的章鱼3 分钟前
Spring的 @Validate注解详细分析
前端·spring boot·算法
zimoyin24 分钟前
Kotlin 协程实战:实现异步值加载委托,对值进行异步懒初始化
java·前端·kotlin
程序员与背包客_CoderZ2 小时前
Node.js异步编程——Callback回调函数实现
前端·javascript·node.js·web
非凡ghost2 小时前
Pale Moon:速度优化的Firefox定制浏览器
前端·firefox
清灵xmf3 小时前
从 Set、Map 到 WeakSet、WeakMap 的进阶之旅
前端·javascript·set·map·weakset·weakmap
11054654013 小时前
11、参数化三维产品设计组件 - /设计与仿真组件/parametric-3d-product-design
前端·3d
爱笑的林羽3 小时前
Mac M系列 安装 jadx-gui
前端·macos
运维@小兵3 小时前
vue使用路由技术实现登录成功后跳转到首页
前端·javascript·vue.js
肠胃炎3 小时前
React构建组件
前端·javascript·react.js
酷爱码4 小时前
HTML5表格语法格式详解
前端·html·html5