5种div 内容水平垂直居中方法

您所在的位置:网站首页 js设置div内容居中 5种div 内容水平垂直居中方法

5种div 内容水平垂直居中方法

2023-06-02 16:58| 来源: 网络整理| 查看: 265

以下是五种让 div 中的内容水平垂直居中的方法:

使用 Flex 布局

使用 Flex 布局是让 div 中的内容水平垂直居中的最常见方法,可以使用以下样式实现:

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

以上样式会将 container 容器中的内容水平、垂直居中。

使用绝对定位

使用绝对定位也可以实现 div 中内容的水平垂直居中,可以使用以下样式实现:

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

以上样式会将 content 容器中的内容水平、垂直居中。

使用 table-cell

使用 table-cell 也可以实现 div 中内容的水平垂直居中,可以使用以下样式实现:

.container { display: table-cell; text-align: center; vertical-align: middle; }

以上样式会将 container 容器中的内容水平、垂直居中。

使用 Grid 布局

使用 Grid 布局也可以实现 div 中内容的水平垂直居中,可以使用以下样式实现:

.container { display: grid; place-items: center; }

以上样式会将 container 容器中的内容水平、垂直居中。

使用 line-height

使用 line-height 属性也可以实现 div 中内容的水平垂直居中,可以使用以下样式实现:

.container { line-height: 100px; /* 修改此处的值为 div 的高度 */ text-align: center; }

以上样式会将 container 容器中的内容水平、垂直居中。

以上五种方法都能实现 div 中内容的水平垂直居中,具体使用哪种方法可以根据具体的项目需求和适用场景来决定。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3