CSS实现居中的几种方案(总结)


当前第2页 返回上一页

在已知元素宽度的情况下,可以使用负边距代替CSS transform。

1

2

3

4

5

.plate {

  position: absolute;

  left: 50%;

  margin-left: -60px;

}

垂直居中

内联元素

Vertical Padding

垂直居中元素最简单的方法之一是使用padding:

1

2

3

  padding-top: 24px;

  padding-bottom: 24px;

}

9.png

Vertical Align

vertical-align属性可用于一个或多个元素。

在此示例中,叉子和刀子应与桌子垂直居中。

1

2

3

4

5

6

7

8

9

.desk {

  text-align: center;

}

 

.plate,

.fork,

.knife {

  vertical-align: middle;

}

Flexbox

为了对齐盘子,叉子和刀,我们可以使用 flexbox:

1

2

3

4

5

.desk {

  display: flex;

  justify-content: center;

  align-items: center;

}

10.png

块元素

绝对定位

通过绝对定位元素,可以使用 CSS transform将元素垂直居中:

1

2

3

4

5

.plate {

  position: absolute;

  top: 50%;

  transform: translateY(-50%);

}

11.png

如果知道元素高度,则可以使用负边距代替transform

1

2

3

4

5

.plate {

  position: absolute;

  top: 50%;

  margin-top: -60px;

}

CSS Grid

使用CSS网格,我们可以使用align-items将项目垂直于其网格区域居中。

1

2

3

4

.desk {

  display: grid;

  align-items: center;

}

12.png

水平垂直居中

内联元素

Padding 和Text Align

1

2

3

4

5

.plate {

  text-align: center;

  padding-top: 24px;

  padding-bottom: 24px;

}

其他元素类型

绝对定位

1

2

3

4

5

6

.plate {

  position: absolute;

  left: 50%;

  top: 50%;

  transform: translate(-50%,-50%);

}

13.png

Flexbox

通过 justify-content:centeralign-items:center 就可以将元素垂直水平居中:

1

2

3

4

5

.plate {

  display: flex;

  justify-content: center;

  align-items: center;

}

CSS Grid

通过place-items属性就可以通过,它结合了justify-contentalign-items:

1

2

3

4

.desk {

  display: grid;

  place-items: center;

}

更多编程相关知识,请访问:编程入门!!

以上就是CSS实现居中的几种方案(总结)的详细内容,更多文章请关注木庄网络博客

返回前面的内容

相关阅读 >>

已知和未知高度下进行垂直水平居中的方法

window对象在前端领域的角色

如何使用css让图片实现半透明的效果

详解css中position属性的用法

css中width有啥属性?

html的基础控件有哪些

css border不显示怎么办

css punctuation-trim属性怎么用

html超链接字体颜色怎么改?超链接字体颜色的更改方法总结

用css怎么添加小图标

更多相关阅读请进入《前端》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...