首页 > 开发 > CSS > 正文

css实现元素水平垂直居中常见的两种方式实例详解

2024-07-11 08:32:14
字体:
来源:转载
供稿:网友

一、父元素的flex布局实现元素的水平垂直居中

示例代码如下:

<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .parent{ display:flex; display:-webkit-flex; justify-content: center; align-items: center; width:100%; height: 200px; background-color: #c43; } .child{ width:300px; height:100px; background-color: #c4235b; } </style></head><body> <div class="parent"> <div class="child"></div> </div></body></html>

效果图如下:

二、绝对定位&负margin值实现元素水平垂直居中

注意:元素本身需要确定宽度和高度

示例代码如下:

<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> div{ width:300px; height:100px; background-color: #873cac; position:absolute; top:50%; left:50%; margin-left: -150px; margin-top:-50px; } </style></head><body> <div></div></body></html>

效果图如下:

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对错新站长站的支持。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表