CSS 元素居中

CSS 页面元素的居中有多种方法,常用的有以下几种:

1.使用 Flexbox 布局:

#parent {
display: flex;
align-items: center;
justify-content: center;
}

2.使用 Grid 布局:

#parent {
display: grid;
place-items: center;
}

3.使用 Grid Layout 和 Grid Template Columns 和 Grid Template Rows:

#parent {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
grid-column: 2/3;
grid-row: 2/3;
}

4.使用 CSS Grid 布局和 Grid Template Columns 和 Grid Template Rows:

#parent {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
}
#child {
grid-column: 2/3;
grid-row: 2/3;
}

5.使用 CSS Grid 布局和 Grid Template Areas:

#parent {
display: grid;
grid-template-areas: ". . ." ". mydiv ." ". . .";
}

6.使用 position 属性和 transform 属性:

#parent {
position: relative;
}
#child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

7.使用 text-align 和 line-height 属性:

#parent {
text-align: center;
}
#child {
display: inline-block;
line-height: 300px; /* 高度值 */
}

8.仅水平居中:

#mydiv {
margin: 0 auto;
width: 200px; /* 元素宽度 */
}

9.仅垂直居中:

#mydiv {
position: absolute;
top: 50%;
transform: translateY(-50%);
}

10.使用 Table 布局:

#mydiv {
display: table;
margin: 0 auto;
}

11.使用 absolute 定位和 calc() 函数:

#mydiv {
position: absolute;
top: calc(50% - 150px); /* 高度的一半 */
left: calc(50% - 150px); /* 宽度的一半 */
width: 300px; /* 自身宽度 */
height: 300px; /* 自身高度 */
}

这些方法中有些需要父元素支持,如 Flexbox 布局和 Grid布局需要在父元素上添加相应的布局。

posted @   飞仔FeiZai  阅读(460)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 百万级群聊的设计实践
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
点击右上角即可分享
微信分享提示