欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

css 垂直居中的几种方式

发布时间:2025/6/17 编程问答 42 豆豆
生活随笔 收集整理的这篇文章主要介绍了 css 垂直居中的几种方式 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

元素示例

<template><div class="margin"style="width: 500px;height: 500px;background-color: yellow"><div class="center"style="width: 200px;height: 200px;background-color: red"></div></div> </template>

 

Part.1  绝对定位 + 百分比

.margin {position: relative; } .center {position: absolute;top: 50%;left: 50%;margin-top: -100px;margin-left: -100px; }

 

Part.2  绝对定位 + transform

.margin {position: relative } .center {position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%) }

 

Part.3  绝对定位 + 0

.margin {position: relative } .center {position: absolute;top: 0;right: 0;bottom: 0;left: 0;margin: auto }

 

 

Part.4  flex

.margin {display: flex;justify-content: center;align-items: center; }

 

Part.5  flex + margin

.margin {display: flex } .center {margin: auto }

转载于:https://www.cnblogs.com/langxiyu/p/11177487.html

总结

以上是生活随笔为你收集整理的css 垂直居中的几种方式的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。