CSS 中的水平和垂直居中

2025-06-07

CSS 中的水平和垂直居中

如果您像我一样,那么在您的职业生涯中,垂直和水平居中 HTML 元素曾经一度成为您的困扰。

幸运的是,这个解决方案适用于所有浏览器,甚至是 IE 11

display: flex;
justify-content: center;
align-items: center;
Enter fullscreen mode Exit fullscreen mode

justify-content默认为水平对齐。删除或设置justify-content: flex-start;会将子元素置于 左侧设置justify-content: flex-end;会将子元素置于右侧

align-items默认为垂直对齐。删除或设置align-items: flex-start;会将子元素置于 顶部设置align-items: flex-end;会将子元素置于底部

这是一个例子

您或许可以停止使用paddingabsolute左/右和上/下定位float、、、line-height以及transform任何其他技巧:)

文章来源:https://dev.to/skhmt/horizo​​ntally-and-vertically-centering-in-css-2248
PREV
4 个实用技巧,助您立即改善 UI 阴影设计(包含设计文件和代码)
NEXT
理解提升