You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The CSS justify-items property defines the default justify-self for all items of the box, giving them all a default way of justifying each box along the appropriate axis.
justify-items属性为所有箱子定义了默认justify-self,给出了在适当的轴上对每个框进行两端对齐的默认方法。
平时工作用肯定会有遇到需要水平和垂直方向都要居中的场景
有次被问到都有哪些方法的时候,一时只想到三种,实在是惭愧,唯有学习+复习一下,心里才稍微踏实一点。
position absolute + margin
这种估计是最早入门的一种方法了
这种方法在 PC 时代应用最广,没什么兼容问题,唯一缺点,需要知道元素的 width, height
缺点,拓展性不好,如果多个子元素的话,会重叠覆盖之前的元素,不够灵活
绝对定位的老毛病,如无特别说明,下面绝对定位的例子,也都有该缺点
position absolute + translate -50%
这种可以理解为上面版本的延伸版本
因为是 css3 属性,PC 上低版本浏览器是不兼容,移动端基本不会有问题
flex 布局
flex 有多好用,根本不用我说了
知识延伸
说到 flex 布局,想起之前被问过一个问题:
你知道 align-items 吧?那知道 justify-items 吗?说说两者的关系?
我内心:justify-items 有这东西吗??好像没有用过啊,蒙了
我:align-items 是垂直方向元素的对齐方向,那 justify 应该是水平方向的吧...
直到后来查了资料
其实是有该属性的,但是该属性并非必要属性,所以网上介绍得也少,阮老师的 flex 文章下也没有介绍该属性,此处说明一下,原来我理解的 flex 布局的水平和垂直方向一直是有不准确的,准确描述应该是主轴和交叉轴(根据 flex-direction 属性的值决定),而非必要是因为主轴可以由开发者自行决定,所以目前使用的 align-items, align-content, align-self 已经是可以满足使用了
更多详见:In CSS Flexbox, why are there no “justify-items” and “justify-self” properties?
更多关于 flex 布局的细节,可以看文末阮一峰老师的链接
position absolute + top, right, bottom, left 0 + margin auto
这个是后来发现的一个黑科技,有点特别,利用绝对定位使盒子四边到父元素距离为0,再设置 margin: auto
需要知道子元素的宽高
css3 calc 属性
这种同样是需要知道元素宽高,且仅适合支持 CSS3 的浏览器版本
inline-block
优点:
缺点:
codepen
writing mode
table 布局
grid 布局
codepen
参考
CSS实现水平垂直居中的1010种方式
Flex 布局教程:语法篇
justify-items - MDN
The text was updated successfully, but these errors were encountered: