tft每日頭條

 > 生活

 > 多個你不知道的css居中方案

多個你不知道的css居中方案

生活 更新时间:2025-08-13 02:25:44

今天,整理下css居中的解決:

多個你不知道的css居中方案(css你想到和想不到的)1

水平居中

對于行内元素(inline):text-align: center;

對于塊級元素(block):設置寬度且 marigin-left 和 margin-right 是設成 auto

對于多個塊級元素:對父元素設置 text-align: center;,對子元素設置 display: inline-block;;或者使用 flex 布局

垂直居中

對于行内元素(inline)

單行:設置上下 pandding 相等;或者設置 line-height 和 height 相等

多行:設置上下 pandding 相等;或者設置 display: table-cell; 和 vertical-align: middle;;或者使用 flex 布局;或者使用僞元素

對于塊級元素(block):下面前兩種方案,父元素需使用相對布局

已知高度:子元素使用絕對布局 top: 50%;,再用負的 margin-top 把子元素往上拉一半的高度

未知高度:子元素使用絕對布局 position: absolute; top: 50%; transform: translateY(-50%);

使用 Flexbox:選擇方向,justify-content: center;

水平垂直居中

定高定寬:先用絕對布局 top: 50%; left: 50%;,再用和寬高的一半相等的負 margin 把子元素回拉

高度和寬度未知:先用絕對布局 top: 50%; left: 50%;,再設置 transform: translate(-50%, -50%);

使用 Flexbox:justify-content: center; align-items: center;

歡迎各位童鞋分享自己總結的别的css居中的解決的方案,分享快樂,哈哈!

,

更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!

查看全部

相关生活资讯推荐

热门生活资讯推荐

网友关注

Copyright 2023-2025 - www.tftnews.com All Rights Reserved