css多种方式实现等宽布局

王景迁 2019-06-30

本文讲的等宽布局是在不手动设置元素宽度的情况下,使用纯css实现各个元素宽度都相当的效果。

1、使用table-cell实现(兼容ie8)

<style>
    body,div{
        margin: 0;
        padding: 0;
    }
    .table-layout{
        display: table;/*父元素必须设置为table*/
        table-layout: fixed;/*这个属性一定要有,否则达不到效果*/
        width: 50%;
        margin: 20px auto;
    }
    .table-cell-layout{
        display: table-cell;/*子元素必须设置为table-cell*/
        height: 40px;
        border: 1px solid #666;
        border-left: none;
    }
    .table-cell-layout:first-child{
        border-left: 1px solid #666;
    }
</style>

<body>
    <ul class="table-layout">
        <li class="table-cell-layout">li1</li>
        <li class="table-cell-layout">li2</li>
        <li class="table-cell-layout">li3</li>
        <li class="table-cell-layout">li4</li>
        <li class="table-cell-layout">li5</li>
    </ul>
</body>

2、使用flex布局来实现

<style>
    body,div{
        margin: 0;
        padding: 0;
    }
    .flex-layout{
        display: flex;
        width: 50%;
        margin: 20px auto;
    }
    .flex-item{
        flex: 1;
        height: 40px;
        border: 1px solid #666;
        border-left: none;
    }
    .flex-item:first-child{
        border-left: 1px solid #666;
    }
</style>

<body>
    <ul class="flex-layout">
        <li class="flex-item">li1</li>
        <li class="flex-item">li2</li>
        <li class="flex-item">li3</li>
        <li class="flex-item">li4</li>
        <li class="flex-item">li5</li>
    </ul>
</body>

相关推荐

aSuncat / 0评论 2020-08-18