[英]Float dropdown elements push each other to the right
我正在开展一个项目,其中一个页面上有多个下拉列表。 为了按顺序获取这些下拉列表,我使用左侧浮动,问题是当我打开左侧的一个下拉列表时,它将其中一些推向右侧。 需要做的是,开放下拉列表下方的下拉列表需要向下移动,而不是向下移动。
我试图使用“clear:both”和“Overflow:auto”,但这些都不起作用。
这是一个JSFiddle: https ://jsfiddle.net/p85ga09f/
var acc = document.getElementsByClassName("accordion"); var i; for (i = 0; i < acc.length; i++) { acc[i].addEventListener("click", function() { this.classList.toggle("active"); var panel = this.nextElementSibling; if (panel.style.maxHeight) { panel.style.maxHeight = null; } else { panel.style.maxHeight = panel.scrollHeight + "px"; } }); }
* { font-family: "Open Sans", "Helvetica Neue", Helvetica, Roboto, Arial, sans-serif; } .accordion_holder { border-bottom: 1px dashed #eaeaea; width: 48%; float: left; margin: 0 1%; } .accordion { background-color: #fff; color: #444; cursor: pointer; padding: 18px; padding-bottom: 30px; width: 100%; border: none; text-align: left; outline: none; font-size: 1.125rem; font-weight: 200; transition: 0.4s; } .panel { padding: 0 18px; background-color: white; max-height: 0; overflow: hidden; transition: max-height 0.2s ease-out; } li { line-height: 28px; } i { margin-right: 10px; } li, a { color: #FF4212; text-decoration: none; } ul { margin: 0; margin-bottom: 5px; }
<div class="content"> <div class="accordion_holder"> <button class="accordion"> Placeholder 1 </button> <div class="panel"> <ul> <a href="#" target="_parent"> <li>test</li> </a> <a href="#" target="_parent"> <li>tset</li> </a> </ul> </div> </div> <div class="accordion_holder"> <button class="accordion"> Placeholder 2 </button> <div class="panel"> <ul> <li> test </li> <li> test </li> <li> test </li> </ul> </div> </div> <div class="accordion_holder"> <button class="accordion"> Placeholder 3 </button> <div class="panel"> <ul> <li> test </li> <li> test </li> </ul> </div> </div> </div>
下拉列表需要保留在行和列上。
任何帮助,将不胜感激。
在每行的左手风琴按钮上使用“clear:left”可以解决您的问题。 因此,在我的情况下,向“占位符3”添加一个“clear:left”的类。
编辑:正如其他人所说; 如果您只有几个按钮,这是一个快速解决方案。 对于较大的手风琴,我建议使用Flexbox或Grid。
只需使用flexbox就可以了 - 添加
display: flex;
flex-wrap: wrap;
到'content'容器,它应该显示你想要的方式: https : //jsfiddle.net/p8e0najc/
也许使用flexbox而不是float是一种选择? 您可以更好地控制项目彼此之间的行为方式。 我喜欢使用的指南是https://css-tricks.com/snippets/css/a-guide-to-flexbox/
您可以使用css网格实现此方法,例如:
.content {
display: grid;
grid-template-columns: 1fr 1fr;
grid-auto-rows: auto;
}
正如评论中已经提到的那样。 了解您是处理动态列表还是知道要渲染的元素数量至关重要。
如果要使用更通用的方法,则应使用Flexbox。 因此,您可以根据需要动态添加任意数量的元素,并保持相同的功能。
但是,如果您想对问题进行快速(也是脏)修复并保留当前解决方案,则还可以指定要下推哪些元素。 看到这里 。
根据小提琴,你只需要设置clear: left
是正确的元素,实际上是第三个元素。 为了更灵活(感谢@ 04FS),您还可以使用这样的类定义:
.accordion_holder:nth-child(2n+1) {
clear: left;
}
我想你想要这样表现出来。 您可以使用弹性框进行此操作。 https://jsfiddle.net/b8s1y629/1/
.content{
display:flex;
flex-wrap: wrap;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.