CSSレイアウト実装テクニック

垂直方向の中央揃え

インライン要素の場合

heightとline-heightの値を同一に設定します。

ブロック要素の場合

絶対位置指定(要素サイズ既知)

.container {
    position: relative;
}
.target-element {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 180px;
    height: 240px;
    margin-left: -90px;
    margin-top: -120px;
}

transformプロパティ(要素サイズ未知)

.wrapper {
    position: relative;
}
.content-box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

Flexboxを使用

.flex-container {
    display: flex;
    justify-content: center;
    align-items: center;
}

Gridレイアウト

.grid-wrapper {
    display: grid;
}
.grid-item {
    justify-self: center;
    align-self: center;
}

テーブル表示

.table-container {
    display: table-cell;
    height: 180px;
    width: 180px;
    text-align: center;
    vertical-align: middle;
}
.table-content {
    display: inline-block;
    width: 80px;
    height: 80px;
}

固定ヘッダーと可変コンテンツレイアウト

Flexbox実装

.page-layout {
    display: flex;
    flex-direction: column;
    height: 100vh;
}
.header-section {
    height: 60px;
}
.main-content {
    flex: 1;
}

絶対位置指定実装

.layout-container {
    position: relative;
    height: 100vh;
}
.header-area {
    height: 60px;
}
.content-area {
    position: absolute;
    top: 60px;
    left: 0;
    right: 0;
    bottom: 0;
}

3カラムレイアウト

Flexbox方式

.three-column {
    display: flex;
    height: 300px;
}
.sidebar-left {
    width: 150px;
    background: #ff6b6b;
}
.main-area {
    flex: 1;
    background: #4ecdc4;
}
.sidebar-right {
    width: 150px;
    background: #45b7d1;
}

絶対位置指定方式

.layout-wrapper {
    position: relative;
    height: 300px;
}
.central-content {
    margin: 0 160px;
    background: #4ecdc4;
}
.left-panel {
    position: absolute;
    left: 0;
    top: 0;
    width: 150px;
    height: 100%;
    background: #ff6b6b;
}
.right-panel {
    position: absolute;
    right: 0;
    top: 0;
    width: 150px;
    height: 100%;
    background: #45b7d1;
}

CSS三角形の作成

.triangle-element {
    width: 0;
    height: 0;
    border: 40px solid;
    border-color: #3498db transparent transparent transparent;
}

フロート解除

.clear-float::after {
    content: "";
    display: table;
    clear: both;
}

その他の実用プロパティ

グラデーション背景

.gradient-bg {
    background: linear-gradient(45deg, #667eea, #764ba2);
}

ボックスシャドウ

.shadow-box {
    box-shadow: 3px 3px 5px 2px rgba(0, 0, 0, 0.15);
}

タグ: CSS レイアウト 垂直中央揃え flexbox Grid

7月2日 00:45 投稿