css 实用技巧 —— div在div中水平垂直居中(两种方法)

简介: css 实用技巧 —— div在div中水平垂直居中(两种方法)

方法一:子绝父相

<template>
    <div class="father">
        <div class="son">
        </div>
    </div>
</template>
<style scoped>
    .father {
        background: red;
        height: 200px;
        position: relative;
    }
 
    .son {
        background: green;
        width: 80%;
        height: 100px;
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        margin: auto;
    }
</style>

实现原理

1. 使用子绝父相定位

2. 默认情况下,绝对定位元素的宽度表现是“包裹性”,宽度由内部尺寸决定,但对于非替换元素,当left/right或top/bottom对立方位的属性值同时存在时,元素的宽度表现为“格式化宽度/高度”  ,margin、border、padding和content内容区域会自动分配水平(和垂直)空间。

方法二:display: table-cell

<template>
    <div class="father">
        <div class="son">
        </div>
    </div>
</template>
<style scoped>
    .father {
        background: red;
        height: 200px;
        width: 200px;
        display: table-cell;
        vertical-align: middle;
    }
 
    .son {
        background: green;
        width: 80%;
        height: 100px;
        margin: 0 auto;
    }
</style>

实现原理

1. 在 display: table-cell 上使用 vertical-align: middle 实现垂直居中

2. 使用 margin: 0 auto; 实现水平居中

目录
相关文章
|
5天前
|
前端开发
css实用技巧——给锚点定位添加偏移
css实用技巧——给锚点定位添加偏移
9 3
|
5天前
|
JavaScript 前端开发 容器
vue组件封装——固定宽高比的容器(2种方法:纯CSS实现 + JS实现)
vue组件封装——固定宽高比的容器(2种方法:纯CSS实现 + JS实现)
9 2
|
5天前
|
前端开发
css 实用技巧 —— 永远居中的弹窗
css 实用技巧 —— 永远居中的弹窗
5 2
|
5天前
|
前端开发
css实用技巧——利用内联元素的padding实现高度可控的分隔线
css实用技巧——利用内联元素的padding实现高度可控的分隔线
8 2
|
5天前
|
前端开发
css 拉伸 resize —— 实现可拉伸的div(含限制拉伸的尺寸)
css 拉伸 resize —— 实现可拉伸的div(含限制拉伸的尺寸)
9 1
|
5天前
|
前端开发
css 实用技巧 —— 文字和图标垂直居中对齐(四种方法)
css 实用技巧 —— 文字和图标垂直居中对齐(四种方法)
13 1
|
5天前
|
前端开发
css 实用技巧 —— 使用border属性绘图(三角形、梯形、对话框尖角)
css 实用技巧 —— 使用border属性绘图(三角形、梯形、对话框尖角)
6 1
|
5天前
|
前端开发
你不知道的css——2. 百分比高度失效,绝对定位和非绝对定位元素的宽高百分比计算方法的不同
你不知道的css——2. 百分比高度失效,绝对定位和非绝对定位元素的宽高百分比计算方法的不同
7 1
|
2天前
|
前端开发 C++ 容器
CSS【详解】居中对齐 (水平居中 vs 垂直居中)
CSS【详解】居中对齐 (水平居中 vs 垂直居中)
7 0
|
5天前
|
前端开发
css div填满剩余高度
css div填满剩余高度
5 0