外链论坛

 找回密码
 立即注册
搜索
查看: 61|回复: 5

CSS常用九种方式实现垂直居中

[复制链接]

2920

主题

1万

回帖

9913万

积分

论坛元老

Rank: 8Rank: 8

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

倘若 .parent 的 height 不写,你只必须 padding: 10px 0; 就能将 .child 垂直居中;

倘若 .parent 的 height 写死了,就很难把 .child 居中,以下是垂直居中的办法

敬告:能不写 height 就千万别写 height。

以下的办法都围绕着该HTML展开

HTML代码

<div class="parent"> <div class="child"> 垂直居中 </div> </div>

1、table自带功能

css

.parent{ border: 1px solid red; height: 600px; } .child{ border: 1px solid green; }

2、absolute + 负margin

.parent{ height: 600px; border: 1px solid red; position: relative; } .child{ border: 1px solid green; width: 300px; position: absolute; top: 50%; left: 50%; margin-left: -150px; margin-top: -50px; }

3、absolute + translate(-50%,-50%)

.parent{ height: 600px; border: 1px solid red; position: relative; } .child{ border: 1px solid green; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); }

4、absolute; + margin: auto;

.parent{ height: 600px; border: 1px solid red; position: relative; } .child{ border: 1px solid green; position: absolute; width: 300px; height: 200px; margin: auto; top: 0; bottom: 0; left: 0; right: 0; }

5、display: flex;

.parent{ height: 600px; border: 3px solid red; display: flex; justify-content: center; align-items: center; } .child{ border: 3px solid green; width: 300px; }

6、inline-block+vertical-aligin

必定要设置行高,否则不生效

.parent{ height: 600px; border: 3px solid red; text-align:center; line-height:600px; } .child{ border: 3px solid green; width: 300px; line-height:100px; display:inline-block; vertical-align:middle; }

7、table-cell

vertical-align 属性设置一个元素的垂直对齐方式。 该属性定义行内元素的基线相针对该元素所在行的基线的垂直对齐。 准许指定负长度值和百分比值。这会使元素降低而不是上升。 在表单元格中,这个属性会设置单元格框中的单元格内容的对齐方式。
.parent{ border: 1px solid red; height: 600px; width:300px; display: table-cell; vertical-align: middle;//垂直 text-align:center;//水平 } .child{ height: 200px; width:100px; border: 1px solid black; display:inline-block; }

8、grid网格布局

参考grid

.parent{ border: 1px solid red; height: 600px; width:30
回复

使用道具 举报

1

主题

659

回帖

-4

积分

限制会员

积分
-4
发表于 2024-8-25 00:58:05 | 显示全部楼层
外贸B2B平台有哪些?
回复

使用道具 举报

0

主题

1万

回帖

1

积分

新手上路

Rank: 1

积分
1
发表于 2024-8-25 02:53:13 | 显示全部楼层
论坛的成功是建立在我们诚恳、务实、高效、创新和团结合作基础上,我们要把这种精神传递下去。
回复

使用道具 举报

0

主题

1万

回帖

1

积分

新手上路

Rank: 1

积分
1
发表于 2024-9-9 14:08:33 | 显示全部楼层
外链发布社区 http://www.fok120.com/
回复

使用道具 举报

2920

主题

1万

回帖

9913万

积分

论坛元老

Rank: 8Rank: 8

积分
99139495
 楼主| 发表于 2024-9-29 13:29:13 | 显示全部楼层
论坛外链网  http://www.fok120.com/
回复

使用道具 举报

2916

主题

1万

回帖

9913万

积分

论坛元老

Rank: 8Rank: 8

积分
99139580
发表于 2024-10-5 05:23:35 | 显示全部楼层
你的努力一定会被看见,相信自己,加油。
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-10-18 21:18 , Processed in 0.085274 second(s), 19 queries .

Powered by Discuz! X3.4

Copyright © 2001-2023, Tencent Cloud.