错误代码实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
background-color: #000;
width: 300px;
display: flex;
margin: 0 auto;
overflow-x: auto;
}
.inner-box {
background-color: bisque;
width: 141px;
height: 340px;
margin-right: 14px;
}
.inner-box:nth-child(1) {
margin-left: 14px;
}
.text {
width: 141px;
}
</style>
</head>
<body>
<div class="box">
<div class="inner-box">
<div class="text">
1
</div>
</div>
<div class="inner-box">
<div class="text">
2
</div>
</div>
<div class="inner-box">
<div class="text">
3
</div>
</div>
<div class="inner-box">
<div class="text">
4
</div>
</div>
<div class="inner-box">
<div class="text">
5
</div>
</div>
</div>
</body>
</html>
效果图:
解决办法:
让最外层的盒子固定宽度,超出部分进行滚动,第二层盒子根据里面的内容进行宽度自适应即可
主要变化的代码:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
background-color: #000;
width: 300px;
margin: 0 auto;
overflow-x: auto;
}
.box2{
display: flex;
width: fit-content;
}
.inner-box {
background-color: bisque;
width: 141px;
height: 340px;
margin-right: 14px;
}
.inner-box:nth-child(1) {
margin-left: 14px;
}
.text {
width: 141px;
}
</style>
</head>
<body>
<div class="box">
<div class="box2">
<div class="inner-box">
<div class="text">
1
</div>
</div>
<div class="inner-box">
<div class="text">
2
</div>
</div>
<div class="inner-box">
<div class="text">
3
</div>
</div>
<div class="inner-box">
<div class="text">
4
</div>
</div>
<div class="inner-box">
<div class="text">
5
</div>
</div>
</div>
</div>
</body>
</html>
效果图: