Multi-column Layout Solution

Posted by RDFrame on Thu, 03 Oct 2019 09:40:19 +0200

I. Fixed Width + Adaptive

Expected results: Fixed left width, adaptive right width
Common code:
html:

<div class="parent">
    <div class="left">
        <p>left menu</p>
    </div>
    <div class="right">
        <li>right item1</li>
        <li>right item2</li>
        <li>right item3</li>
    </div>
</div>

css:

html, body, p, ul, li {
    margin: 0;
    padding: 0;
}
div.left {
    background: #d2e3e3;
}
div.right {
    background: #77DBDB;
}

Scheme 1: float

.left {
    float: left;
    width: 100px;
}
.right {
    margin-left: 100px; // Or overflow: hidden
}

Option 2: table

.parent {
    display: table;
    width: 100%;
    table-layout: fixed; // https://blog.csdn.net/qq_36699230/article/details/80658742
    .left, .right {
        display: table-cell;
    }
    .left {
        width: 100px;
    }
}

Option three: flex

.parent {
    display: flex;
    .left {
        width: 100px; // Or flex: 0 000 100 px;
    }
    .right {
        flex: 1;
    }
}
  • Two (multiple) columns with fixed width and adaptive layout can be used in the above scheme, and the setting of the middle column can be consistent with that of the first column.
  • Variable width (two or more columns) plus adaptive layout can be achieved by using the above scheme. For the middle column, the setting is consistent with the first column. The difference is that no special width setting is required. Special attention should be paid to the use of table layout, as follows:
.parent {
    display: table;
    width: 100%;
    // Setting table-layout: fixed; equals the cell width, so it is not set here
    .left, .right {
        display: table-cell;
    }
    .left {
        width: 0.1%; // The width is set to a minimum because table-layout: fixed is not set; so the width is determined by the content.
        white-space:nowrap;
    }
}

II. Equal Width (Two/Multiple Columns) Layout

Common code:
html

<div class="parent">
    <div class="column">
        <p>1</p>
    </div>
    <div class="column">
        <p>2</p>
    </div>
    <div class="column">
        <p>3</p>
    </div>
    <div class="column">
        <p>4</p>
    </div>
</div>

css

html, body, div, p {
    margin: 0;
    padding: 0;
}
.parent {
    width: 800px;
    border: 1px solid coral;
    .column {
        height: 30px;
        background: bisque;
        p {
            background: #f0b979;
            height: 30px;
        }
    }
}

Solution 1: float.

.parent {
    margin-left: -20px;
    overflow: hidden;
    .column {
        float: left;
        width: 25%;
        padding-left: 20px;
        box-sizing: border-box;
    }
}


Solution 2: flex (recommended)

.parent {
    display: flex;
    .column {
        flex: 1;
        &+.column {
            margin-left: 10px;
        }
    }
}

3. Contour layout

Recommended solutions:

.parent {
    display: flex;
}
.left, .right {
    flex: 1;
}

Topics: Front-end