css兄弟元素跟随宽度最长的元素等宽?

红色跟灰色的元素宽度需要跟随绿色元素的宽度撑满一致,如下:
image.png
现有代码:

<!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>
</head>
<style>
    .container{
        width: 100%;
        overflow-x: auto;
    }
    .item1{
        background: red;
    }
    .item2{
        background: gray;
    }
    .item3{
        min-width: 1300px;
        background: greenyellow;
    }
</style>
<body>
    <div class="container">
        <div class="item1">item1</div>
        <div class="item2">item2</div>
        <div class="item3">item3</div>
    </div>
</body>
</html>

请教各路大神最简便方法

阅读 3.2k
2 个回答

其实很简单啦,给 .container 元素设置 width: fit-content 就好了。但是滚动条就会出现在 body 元素上。
所以可以在 .container 外部再套一层 div 就好了。

以下是代码结构

<!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>
</head>
<style>
    .wrap { 
        width: 100%;
        overflow-x: auto;
    }
    .container{
        width: fit-content;
    }
    .item1{
        background: red;
    }
    .item2{
        background: gray;
    }
    .item3{
        min-width: 1300px;
        background: greenyellow;
    }
</style>
<body>
    <div class="wrap">
        <div class="container">
            <div class="item1">item1</div>
            <div class="item2">item2</div>
            <div class="item3">item3</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>
</head>
<style>
    .outer {
        overflow-x: auto;
    }
    .container {
        min-width: 1300px;
    }

    .item1 {
        background: red;
    }

    .item2 {
        background: gray;
    }

    .item3 {

        background: greenyellow;
    }
</style>

<body>
    <div class="outer">
        <div class="container">
            <div class="item1">item1</div>
            <div class="item2">item2</div>
            <div class="item3">item3</div>
        </div>
    </div>
</body>

</html>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题