html元素分为block元素和inline元素。
- inline元素水平居中
设置外层元素的text-align: center
- block元素水平居中
- 设置元素自身的样式margin: 0 auto
- 设置父元素display: flex; justify-content: center;
- block元素水平垂直居中 定宽 (子元素宽高100px)
- 设置父元素的position: relative, 子元素position: absolute, top: 50%, left 50%, margin: -100px, 0, 0 -100px.
- block元素水平垂直居中 不定宽,将定宽的子元素的margin改为
transform: translate(-50%, -50%)。
本文详细介绍了HTML元素的居中布局策略,包括inline元素和block元素的水平及垂直居中方法。对于inline元素,可以设置外层元素text-align为center;而对于block元素,可以使用margin: 0 auto实现水平居中,或者通过display: flex和justify-content: center进行布局。在垂直居中方面,固定宽度的block元素可以通过相对定位和负边距调整,而不定宽元素则可以利用transform: translate(-50%,-50%)实现居中效果。
2万+

被折叠的 条评论
为什么被折叠?



