我有5个内联的正方形在一个灵活的父母.当点击按钮时,first方块被移除.每次移除第一个方块时,后面的方块都会被推回左边一个方块的宽度(正如预期的那样).发生这种情况时,是否有可能使其他方块保持其位置(即,它们停留在原来的位置,而不是向左移动)?
我能想到的一种方法是绝对定位每个正方形元素.但这是防止方块移动的唯一方法吗?
Note:如果我也移除last方块,我希望方块保持它们的位置;所以像justify-content: flex-end
这样的东西不能满足我的需求,因为它不能同时满足两种情况.
Note 2:visibility: hidden
或opacity: 0
也不能满足我的需要,因为我确实需要删除正方形元素.我还计划稍后添加另一个方形元素,不希望布局发生变化.这可能吗?
请看小提琴的例子.
$('.click-me').on('click', function() {
// Remove the first square.
$('.main').children().first().remove();
});
.main {
position: relative;
display: flex;
margin-top: 20px;
}
.main span {
width: 35px;
height: 35px;
background-color: #2e852e;
border: 1px solid #000;
}
.main .square1,
.main .square5 {
background-color: #a5a551;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="click-me">Click Me!</button>
<div class="main">
<span class="square1"></span>
<span class="square2"></span>
<span class="square3"></span>
<span class="square4"></span>
<span class="square5"></span>
</div>