我正在尝试使用 HTML 和 CSS 获得一个可扩展按钮以适应网格,但它们不适合。我对 HTML 和 CSS 还是很陌生,所以我不确定我做错了什么。我有一种我喜欢的按钮样式,但我终生无法让它们整齐地放入网格中。
[绑定以摆脱按钮之间的空格][1]
<style>
.grid-container {
display: grid;
grid-template: auto / auto auto auto auto;
background-color: gray;
padding: 10px;
}
.collapsible {
background-color: #f1f1f1;
gap: 15px
cursor: pointer;
padding: 18px;
Border-radius: 15px;
border: none;
text-align: left;
outline: none;
font-size: 15px;
}
.active, .collapsible:hover {
background-color: #555;
}
.collapsible:after {
content: '\002B';
font-weight: bold;
float: right;
margin-left: 5px;
}
.active:after {
content: "\2212";
}
.content {
padding: 0 18px;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
background-color: #f1f1f1;
border-radius: 15px;
}
</style>
<div class= "grid-container">
<button class="collapsible">Open Collapsible</button>
<div class="content">
<p> Test </p>
</div>
<button class="collapsible">Open Collapsible</button>
<div class="content">
<p> Test </p>
</div>
</div>
<script>
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.maxHeight){
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
}
});
}
</script>
[1]: https://i.stack.imgur.com/djtYl.png
出现空格是因为元素内容仍然占据着你不可见的空间。如果要删除按钮之间的空格,首先将内容元素显示为无,然后如果切换了活动类,则向其添加一些样式以显示内容。这是例子。
.content {
padding: 0 18px;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
background-color: #f1f1f1;
border-radius: 15px;
display: none; <-- new added
}
.active + .content { <-- new added
display: block;
}
我认为这应该有效。希望有帮助。