【问题标题】:CSS Flexbox: flex item grow when changing another flex items positionCSS Flexbox:更改另一个弹性项目位置时弹性项目增长
【发布时间】:2016-12-05 19:24:35
【问题描述】:
在下面的示例中,我有 3 个弹性项目。我想要做的是当我改变蓝色的位置时让绿色的生长。我找不到用 CSS 做的方法,还是应该用 JS 手动编写。
$(document).ready(function(){
$("#btnStart").click(function(){
$("#three").addClass("slide-right");
});
});
main {
display: flex;
flex-flow: row no-wrap;
width: 100%;
height: 500px;
justify-content: flex-start;
overflow: hidden;
}
div {
position: relative;
}
#one {
width: 200px;
background-color: red;
}
#two {
flex: 1;
background-color: green;
}
#three {
width: 200px;
background-color: blue;
left: 0;
transition: left 400ms;
}
#three.slide-right {
left: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="button" id="btnStart" value="Start" />
<main>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
</main>
【问题讨论】:
标签:
javascript
css
flexbox
【解决方案1】:
因为div的位置是relative,所以改变left属性不会改变布局。
根据MDN article about position:
相对
此关键字将所有元素布置为好像该元素不是
定位,然后调整元素的位置,不改变
布局(从而为它应该拥有的元素留下一个间隙
如果它没有被定位)。位置的影响:相对于
table-*-group、table-row、table-column、table-cell 和 table-caption
元素未定义。
如果你不想改变元素本身的宽度,因为你想让它滑动。您可以将其包装在容器中,并更改容器的宽度(参见代码 sn-p)。
$(document).ready(function() {
$("#btnStart").click(function() {
$("#threeContainer").addClass("slide-right");
});
});
main {
display: flex;
flex-flow: row no-wrap;
width: 100%;
height: 500px;
justify-content: flex-start;
overflow: hidden;
}
#one {
width: 200px;
background-color: red;
}
#two {
flex: 1;
background-color: green;
}
#threeContainer {
width: 200px;
transition: width 400ms;
}
#threeContainer.slide-right {
width: 0;
}
#three {
height: 100%;
width: 200px;
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="button" id="btnStart" value="Start" />
<main>
<div id="one"></div>
<div id="two"></div>
<div id="threeContainer">
<div id="three">
I'm an example text that won't change when #three slides
</div>
</div>
</main>
【解决方案2】:
由于元素只在屏幕上移动,它使用的初始空间不可用。
您可以使用负边距来释放一些空间,看起来像拉绿色元素。
$(document).ready(function(){
$("#btnStart").click(function(){
$("#three").addClass("slide-right");
});
});
main {
display: flex;
flex-flow: row no-wrap;
width: 100%;
height: 500px;
justify-content: flex-start;
overflow: hidden;
}
div {
position: relative;
}
#one {
width: 200px;
background-color: red;
}
#two {
flex: 1;
background-color: green;
}
#three {
width: 200px;
background-color: blue;
left: 0;
transition: left 400ms;
}
#three.slide-right {
left: 200px;
margin-left:-200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="button" id="btnStart" value="Start" />
<main>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
</main>