我正在制作一个“ Accordion ”小部件,它可以包含任意数量的子项。当子元素关闭时,它会缩小到其标题的高度。当它打开时,它会将其高度分布为与其周围其他打开的 sibling 相同。我相信您以前见过这种类型的东西 - 如果这没有意义,请单击下面的代码笔。
这似乎是 flexbox 的一个很好的候选者(虽然我不是专家)。我想出了这个,它使用 flex-grow 并且在 Firefox 和 Chrome 中完全按照我想要的方式工作,但在 Safari 中却不行。如果垂直空间已被占用,Safari 似乎不会展开子项 - 因此在您打开一个元素后,您无法轻松打开第二个。
<div class="wrapper">
<div class="item">
<h3>foo</h3>
<p>Lorem ipsum</p>
</div>
<div class="item">
<h3>foo</h3>
<p>Lorem ipsum</p>
</div>
<div class="item">
<h3>foo</h3>
<p>Lorem ipsum</p>
</div>
<div class="item">
<h3>foo</h3>
<p>Lorem ipsum</p>
</div>
</div>
.wrapper
display: flex
flex-direction: column
.item
// this is the closed height
flex-basis: 20px
flex-grow: 0
transition: flex-grow .3s ease-out
&.open
flex-grow: 1
https://codepen.io/suchesuch/pen/EEazdV
有谁知道我可以解决这个问题的方法,或者我可以修改其他 CSS 属性以获得相同的结果吗?
明确地说,我正在寻找一个(理想情况下优雅但不一定是)CSS 解决方案。我不想在 JS 中计算高度,因为这会在代码库的其余部分变得丑陋。
感谢阅读!
最佳答案
你必须使用-webkit前缀
.flex-item {
-webkit-flex-grow: ; /* Safari */
flex-grow: ;
}
这里对 flex 有很好的描述。 https://scotch.io/tutorials/a-visual-guide-to-css3-flexbox-properties#flex-grow
来自你的codepen
// the main workings
.wrapper
display: flex
display: -webkit-flex
flex-direction: column
-webkit-flex-direction: column
.item
// this is the closed height
flex-basis: 20px
-webkit-flex-basis: 20px
flex-grow: 0
// safari specific
-webkit-flex-grow: 0
transition: flex-grow .3s ease-out
&.open
flex-grow: 1
-webkit-flex-grow: 1
// boring stuff for display etc
.wrapper
height: 300px
width: 100px
border: 1px solid black
.item
position: relative
h3
height: 20px
padding: 0
margin: 0
background: lightgreen
cursor: pointer
&.open h3
background: lightblue
p
position: absolute
top: 20px
left: 0
right: 0
bottom: 0
background: yellow
margin: 0
padding: 0
overflow: hidden
关于css - 有没有我可以使用的替代 CSS 技术来解决 Safari 对 flex-grow 的不完整支持?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49214389/