野花--css实现元素竖向排列 --- writing-mode和flex的区别
我是在做小米商店首页的侧边栏hover显示时碰到的这个要求,因为想尽量简洁架构,因此侧边栏hover出来的页面也想放在侧边栏的 li元素中,所以就出现了一个限制条件,即li是有宽度限制的,同时li所在的父元素也是有宽度限制的,在第一次尝试使用flex做纵向排列时,出现了背景色不能按照flex纵向排列延伸显示出来,如图示,hover出来的页面是flex纵向排列,但是背景色白色并没有同样显示在自动换列上.
第一种:使用flex方法
前提条件1.爷元素有宽度 2父元素有高度 3.子元素有宽度和高度:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | .top_box { width : 50px ; } .box { background-color : #9bceea ; height : 120px ; flex-wrap: wrap; display : flex; flex- direction : column; .item { height : 40px ; width : 50px ; background-color : #8F41E9 ; } } <div class= "top_box" > <div class= "box" > <div class= "item" >第 1 项</div> <div class= "item" >第 2 项</div> <div class= "item" >第 3 项</div> <div class= "item" >第 4 项</div> <div class= "item" >第 5 项</div> <div class= "item" >第 6 项</div> <div class= "item" >第 7 项</div> <div class= "item" >第 8 项</div> <div class= "item" >第 9 项</div> <div class= "item" >第 10 项</div> <div class= "item" >第 11 项</div> </div> </div> |
运行确实是纵向排列,然后因为高度限制,自动换列,直到结束最后一个div排列.
但是上述有一个问题,就是.box的背景并没有显示出来,按照我的诉求,应该要显示box的背景在整个div中.右下角并没有将背景色显示出来,这个就是flex布局在有高度和宽度限制条件下,纵向排列的局限性.
第二种方法:writing-mode属性结合float
让列表内元素竖着排列,高度不够,纵向换行的需求。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | .top_box { width : 50px ; } .box { background-color : #9bceea ; height : 120px ; writing-mode: vertical-lr; .item { float : left ; writing-mode: initial; height : 40px ; width : 50px ; background-color : #8F41E9 ; } } <div class= "top_box" > <div class= "box" > <div class= "item" >第 1 项</div> <div class= "item" >第 2 项</div> <div class= "item" >第 3 项</div> <div class= "item" >第 4 项</div> <div class= "item" >第 5 项</div> <div class= "item" >第 6 项</div> <div class= "item" >第 7 项</div> <div class= "item" >第 8 项</div> <div class= "item" >第 9 项</div> <div class= "item" >第 10 项</div> <div class= "item" >第 11 项</div> </div> </div> |
如果只有父元素中有writing-mode属性,子元素中没有writing-mode属性,哪么文字也会纵向排列,就像这样
因此,需要在子项中添加writing-mode属性值initial还原成初始的文字排列
这样就实现了纵向排列,自动换行,同时父级元素的背景也延伸显示出来了.
具体原理还不清楚,是经过多次尝试才确定的解决方法.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通