flex弹性盒子,2009年由w3c的大佬提出,轻松的实现web布局方式,并且在pc端也能很好的实现缩放。他取代了之前的 “display+float+position”的布局形式。
今天就介绍介几个有弹性盒子实现的小案例:
这里为了看到效果添加了JS部分
1.固定底部内容
当内容不足浏览器高度时,底部内容要固定在浏览器底部,内容超出浏览器时底部内容要往后推移。之前要实现这一效果需要通过JS来获取浏览器高度进行运算来实现。
html部分
<div class="wrapper">
<div class="head">
<h1>头部内容</h1>
</div>
<div class="content"></div>
<div class="bottom">
<h1>底部内容</h1>
</div>
</div>
css部分
.wrapper{
width: 100%;
display: flex;
flex-direction: column;
background-color: #202020;
}
.head .bottom{
display: flex;
justify-content: center;
}
.content{
color: #bdbdbd;
display: auto;
}
.bottom{
flex-shrink: 0;
}
h1{
background-color: #82fcfd;
padding: 15px;
}
JS部分
var height = 0;
document.getElementsByClassName("head")[0].onclick = function(){
height += 10;
document.getElementsByClassName("content")[0].style.height = `${height}px`;
}
效果:
2.ul li 列表
<ul class="list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
.list{
width: 1800px;
display: flex;
flex-direction: row;
}
.list li{
width: 50px;
height: 50px;
text-align: center;
line-height: 50px;
list-style: none;
background-color: mediumspringgreen;
margin-left: 10px;
}
.list li:hover{
background-color: mediumpurple;
}
效果
轻轻松松试写出一个ul列表,无论怎么改变大小列表都会保持原样。
3.水平折叠容器
html部分
<div id="container" class="horizontal-container">
<div class="fixed-size"> 1</div>
<div class="fixed-size"> 2</div>
<div class="fixed-size"> 3</div>
</div>
<button id="increase-size">增加</button>
<button id="decrease-size">减少</button>
css部分
.horizontal-container {
display: flex;
width: 400px;
flex-flow: row wrap;
}
.fixed-size {
flex: none;
width: 100px;
background-color: black;
color: white;
text-align: center;
margin: 10px 10px;
}
JS部分
var width = 400;
document.getElementById('increase-size').onclick=function() {
width += 100;
if (width > 400) width = 400;
document.getElementById('container').style.width = (width + "px");
}
document.getElementById('decrease-size').onclick=function() {
width -= 100;
if (width < 100) width = 100;
document.getElementById('container').style.width = (width + "px");
}
效果