子元素寬度不確定的情況下實(shí)現(xiàn)橫向滾動(dòng)
開發(fā)中經(jīng)常會(huì)遇到橫向滾動(dòng)的需求,有時(shí)是已經(jīng)確定了子元素個(gè)數(shù)(父元素的寬度自然也就確定),給父元素的父盒子設(shè)置overflow: scroll/auto即可。
一、子元素的數(shù)量不確定導(dǎo)致寬度不確定。
- js實(shí)現(xiàn),首先獲取子元素的個(gè)數(shù),計(jì)算父元素的總寬度,給外層盒子設(shè)置overflow: scroll/auto。具體實(shí)現(xiàn)不在贅述。
- css實(shí)現(xiàn)方式。
<div class="box">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
* {
padding: 0;
margin: 0;
}
html,
body {
width: 100%;
}
.box {
width: 100%;
overflow: scroll;
height: 220px;
}
/* 隱藏滾動(dòng)條 */
.box::-webkit-scrollbar {
display: none;
}
ul {
/* flex布局使子元素橫向排列 */
display: flex;
/* 浮動(dòng)使其脫離文檔流 子元素的寬度就不會(huì)受flex的影響 而且父元素的寬度會(huì)自動(dòng)撐開*/
float: left;
height: 100%;
}
li {
width: 200px;
height: 200px;
list-style: none;
background-color: pink;
margin: 10px 10px;
}
/*
另一種更好的方式(來自評(píng)論區(qū)的反饋)
*/
ul {
display: flex;
}
li {
flex-shrink: 0;
width: 200px;
height: 200px;
}
- display: -webkit-box實(shí)現(xiàn)
<div class="slide-box">
<div class="slide-item"></div>
<div class="slide-item"></div>
<div class="slide-item"></div>
<div class="slide-item"></div>
<div class="slide-item"></div>
</div>
.slide-box{
display: -webkit-box;
overflow-x: scroll;
-webkit-overflow-scrolling:touch;
}
.slide-item{
width: 200px;
height: 200px;
border:1px solid #ccc;
margin-right: 30px;
}
二、 以上方式是針對(duì)每個(gè)子元素寬度確定的情況下,如果每個(gè)子元素的寬度和數(shù)量不確定,則可使用如下方式:
<div class="box">
<ul>
<li>雙方的</li>
<li>是否</li>
<li>沙發(fā)上</li>
<li>水電費(fèi)是</li>
<li>否</li>
<li>否放松的方式</li>
<li>否雙方的</li>
</ul>
</div>
.box {
width: 100vw;
height: 100px;
background-color: pink;
overflow: scroll; /* 關(guān)鍵 */
}
ul {
height: 100%;
white-space: nowrap; /* 關(guān)鍵 */
}
li {
display: inline-block; /* 關(guān)鍵 */
min-width: 60px;
box-sizing: content-box;
padding: 0 20px;
background-color: orange;
height: 50px;
list-style: none;
margin: 30px 10px;
text-align: center;
line-height: 50px;
}
flex 實(shí)現(xiàn)方式:
.box {
width: 100%;
height: 200px;
border: 1px solid #ccc;
overflow: scroll;
}
ul {
display: flex;
}
li {
min-width: 100px;
box-sizing: content-box;
flex-shrink: 0; /* 關(guān)鍵 */
list-style: none;
padding: 0 50px;
}
以上兩種情況,使用flex布局,有個(gè)缺點(diǎn)是如果給子元素設(shè)置了margin,那么最后一個(gè)子元素的margin-right是無效的。

white-space