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

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

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; */
        }
相关推荐
岱宗夫up7 小时前
FastAPI入门(上篇):快速构建高性能Python Web API
开发语言·前端·python·fastapi
紫陌涵光8 小时前
112. 路径总和
java·前端·算法
漠月瑾-西安8 小时前
CVE-2025-55182漏洞解析:你的React项目安全吗?
前端·安全·react.js
No丶slovenly8 小时前
flutter笔记-输入框
前端·笔记·flutter
国产化创客9 小时前
ESP32+Web实现智能气象站
前端·物联网·智能家居·智能硬件
coderYYY10 小时前
VSCode终端启动报错
前端·ide·vscode·npm·编辑器
tod11310 小时前
Redis 数据类型与 C++ 客户端实践指南(redis-plus-plus)
前端·c++·redis·bootstrap·html
Sylvia33.10 小时前
火星数据:棒球数据API
java·前端·人工智能
weixin1997010801611 小时前
1688商品详情页前端性能优化实战
前端·性能优化
DEMO派11 小时前
前端常用XSS攻击演示与防御方案解析
前端·xss