外链论坛

 找回密码
 立即注册
搜索
查看: 40|回复: 0

css 实现水平垂直居中的三种常用办法

[复制链接]

2633

主题

210

回帖

9778万

积分

论坛元老

Rank: 8Rank: 8

积分
97780516
发表于 2024-6-30 05:30:47 | 显示全部楼层 |阅读模式

css 实现水平垂直居中的三种常用办法

首要基本结构样式

<body> <div class="box"> <span></span> </div> </body>

使里面的span元素(粉色圆点)水平垂直居中于其div父元素(淘宝色正方形)

实现的效果图如下:

下面是常用的三种办法

1.定位

<style> * { margin: 0; padding: 0; } .box { width: 100px; height: 100px; bac公斤round: #f40; position: relative; margin: 200px auto; } .box span{ width: 20px; height: 20px; bac公斤round: pink; border-radius: 50%; position: absolute; left: 50%; margin-left: -10px; top:50%; margin-top: -10px; ​ } </style>

2.flex 设置主轴及侧轴方向居中

<style> * { margin: 0; padding: 0; } .box { width: 100px; height: 100px; bac公斤round: #f40; margin: 200px auto; display: flex; justify-content: center; align-items: center; } .box span{ width: 20px; height: 20px; bac公斤round: pink; border-radius: 50%; } </style>

3.最简单,最直接,最牛逼

直接在子元素span下设置 margin : auto;就可

<style> * { margin: 0; padding: 0; } .box { width: 100px; height: 100px; bac公斤round: #f40; margin: 200px auto; display: flex; } .box span{ width: 20px; height: 20px; bac公斤round: pink; border-radius: 50%; margin: auto; } </style>

总结:

以上三种办法咱们实质场景中经常会用到,因此咱们熟悉把握

还有我个人意见运用后两种,不意见运用第1种,后两种简单,采用flex布局,避免用定位。

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

站点统计|Archiver|手机版|小黑屋|外链论坛 ( 非经营性网站 )|网站地图

GMT+8, 2024-10-3 19:20 , Processed in 0.769186 second(s), 40 queries .

Powered by Discuz! X3.4

Copyright © 2001-2023, Tencent Cloud.