怎么在css中利用Flex制作一個柱狀圖?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
HTML:
<div class="his_box"> <div>成績分布直方圖</div> <div class="histogram"> <div><div>10</div></div> <div><div>8</div></div> <div><div>15</div></div> <div><div>12</div></div> <div><div>5</div></div> </div> </div>
CSS:
.his_box{ /*盒子*/
width: 400px;
height: 220px;
border: solid 1px #1E90FF;
display: flex;
flex-direction: column;
align-items: center;
}
.histogram{ /*直方圖*/
display: flex;
}
.histogram>div{ /*一條圖塊*/
width: 30px;
height: 200px; /*100%時的塊高度*/
font-size: 14px;
text-align: center;
margin-right: 5px;
display: flex;
flex-direction: column-reverse;
}
.histogram>div:nth-child(3n) div{ /*圖塊顏色*/
background-color: #ff404b;
}
.histogram>div:nth-child(3n+1) div{
background-color: #99CCFF;
}
.histogram>div:nth-child(3n+2) div{
background-color: #F0AD4E;
}
.histogram>div:nth-child(1) div{
flex: 0 0 50%; /*20為100%,50%就是10*/
}
.histogram>div:nth-child(2) div{
flex: 0 0 40%; /*8/20*/
}
.histogram>div:nth-child(3) div{
flex: 0 0 75%; /*15/20*/
}
.histogram>div:nth-child(4) div{
flex: 0 0 60%; /*12/20*/
}
.histogram>div:nth-child(5) div{
flex: 0 0 25%; /*5/20*/
}本例中,圖塊的最高點為20,每條柱子的高度按比例定義:第1條數據為10,高度是50%;第2條數據為8,高度為40%,以此類推。
圖塊顏色采用3色循環使用。
布局時,最外層容器使用了align-items: center;使容器內元素整體居中。
直方圖模塊使用了display: flex;讓模塊中的柱子橫向排列。
每條柱子也是flex模塊,但它的布局方向是縱向的,且方向是從下到上的 flex-direction: column-reverse;
如果想做成縱向排列的直方圖:

CSS:
.his_box{ /*盒子*/
width: 400px;
height: 220px;
border: solid 1px #1E90FF;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.his_box>div{
text-align: center;
}
.histogram{ /*直方圖*/
display: flex;
flex-direction: column;
}
.histogram>div{ /*一條圖塊*/
height: 30px;
width: 200px; /*100%時的塊寬度*/
line-height: 30px;
font-size: 14px;
text-align: right;
margin-bottom: 5px;
display: flex;
}
.histogram>div:nth-child(3n) div{ /*圖塊顏色*/
background-color: #ff404b;
}
.histogram>div:nth-child(3n+1) div{
background-color: #99CCFF;
}
.histogram>div:nth-child(3n+2) div{
background-color: #F0AD4E;
}
.histogram>div:nth-child(1) div{
flex: 0 0 50%; /*20為100%,50%就是10*/
}
.histogram>div:nth-child(2) div{
flex: 0 0 40%; /*8/20*/
}
.histogram>div:nth-child(3) div{
flex: 0 0 75%; /*15/20*/
}
.histogram>div:nth-child(4) div{
flex: 0 0 60%; /*12/20*/
}
.histogram>div:nth-child(5) div{
flex: 0 0 25%; /*5/20*/
}看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。