两列自适应布局

两列自适应布局是指左(右)侧有一个宽度固定的侧边栏,另一列宽度自适应。

一般我们有以下4种实现方式,废话不多说,直接上代码:

  • 通过将aside浮动,然后设置main的margin来实现
<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <title>两列自适应布局</title>
    <style>
        .wrapper {
            height: 300px;
        }

        .aside {
            float: left;
            height: 100%;
            width: 200px;
            background: red;
        }

        .main {
            margin-left: 210px;
            height: 100%;
            background: blue;
        }
    </style>
</head>

<body>
    <section class="wrapper">
        <aside class="aside"></aside>
        <section class="main">
            main main main main main main
        </section>
    </section>
</body>

</html>
  • 将aside浮动, 再将main设置为overflow: auto,触发BFC形成独立区域,达到效果。
<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <title>两列自适应布局</title>
    <style>
        .wrapper {
            height: 300px;
        }

        .aside {
            height: 100%;
            width: 200px;
            background: red;
            margin-right: 10px;
            float: left;
        }

        .main {
            overflow: auto;
            height: 100%;
            background: blue;
        }
    </style>
</head>

<body>
    <section class="wrapper">
        <aside class="aside"></aside>
        <section class="main">
            main main main main main main
        </section>
    </section>
</body>

</html>
  • 将aside设置为绝对定位,然后通过设置aside的width和wrapper的padding来实现
<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <title>两列自适应布局</title>
    <style>
        .wrapper {
            position: relative;
            padding-left: 210px;
            height: 300px;
        }

        .aside {
            position: absolute;
            left: 0;
            width: 200px;
            height: 100%;
            background: red;
        }

        .main {
            width: 100%;
            height: 100%;
            background: blue;
        }
    </style>
</head>

<body>
    <section class="wrapper">
        <aside class="aside"></aside>
        <section class="main">
            main main main main main main
        </section>
    </section>
</body>

</html>
  • 弹性布局
<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <title>两列自适应布局</title>
    <style>
        .wrapper {
            display: flex;
            height: 300px;
        }

        .aside {
            width: 200px;
            margin-right: 10px;
            background: red;
        }

        .main {
            flex: 1;
            background: blue;
        }
    </style>
</head>

<body>
    <section class="wrapper">
        <aside class="aside"></aside>
        <section class="main">
            main main main main main main
        </section>
    </section>
</body>

</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容