外链论坛

 找回密码
 立即注册
搜索
查看: 57|回复: 1

css水平垂直居中办法

[复制链接]

2659

主题

220

回帖

9910万

积分

论坛元老

Rank: 8Rank: 8

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

按照现有状况选取水平垂直居中的办法

1、父元素定宽定高

(1)块级元素

办法1、子元素position:relative;top:50%;left:50%;transform:translate(-50%,-50%);能够不消事先晓得父元素的宽高,就可实现居中,然则这个办法兼容性较差。

.parent{ width:400px; height:400px; bac公斤round:yellow; } .child{ width:200px; height:200px; bac公斤round:red; position:relative; top:50%; left:50%; transform: translate(-50%,-50%); }

办法2、绝对定位居中,子元素position:absolute;left:0;right:0;top:0;bottom:0;margin:auto;父元素position:relative;兼容性较好。

.parent{ width:400px; height:400px; bac公斤round:yellow; position:relative; } .child{ width:200px; height:200px; bac公斤round:red; position:absolute; left:0; right:0; top:0; bottom:0; margin:auto;

办法3、父元素display: flex;justify-content: center;align-items: center;移动端页面经常用。

.parent{ width:400px; height:400px; bac公斤round:yellow; display: flex; justify-content: center; align-items: center; } .child{ width:200px; height:200px; bac公斤round:red; }

办法四:利用伪元素,让子元素display:inline-block;vertical-align: middle;,再让父元素的伪元素height: 100%;display: inline-block;vertical-align: middle;

.parent{ width:400px; height:400px; bac公斤round:red; text-align:center; } .child{ width:200px; height:200px; bac公斤round:yellow; display:inline-block; vertical-align: middle; } .parent::before { content: ; height: 100%; display: inline-block; vertical-align: middle; }

(2)内联元素

办法1、跟上面的display:flex办法同样运用flex办法块级元素能实现居中,内联元素能实现居中。

.parent{ width:400px; height:400px; bac公斤round:red; display: flex; justify-content: center; align-items: center; } .child{ bac公斤round:yellow; }

办法2、父元素用text-align:center;水平居中,子元素用line-height: 父元素的高度;垂直居中,这个经常用,个人觉得是除flex外最好的办法然则重视:内容必要是单行才可用,倘若多行就不可用了。

.parent{ width:400px; height:400px; bac公斤round:red; text-align:center; } .child{ bac公斤round:yellow; line-height: 400px; }

办法3、父元素display:table-cell;text-align: center;vert

回复

使用道具 举报

8

主题

592

回帖

-19

积分

限制会员

积分
-19
发表于 2024-9-4 14:35:40 | 显示全部楼层
你说得对,我们一起加油,未来可期。
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-10-5 12:01 , Processed in 0.067491 second(s), 19 queries .

Powered by Discuz! X3.4

Copyright © 2001-2023, Tencent Cloud.