文章目录

  1. 使用绝对定位和负外边距对块级元素进行垂直居中
<style>
    #box {
        width: 300px;
        height: 300px;
        background: #ddd;
        position: relative;
    }
    #inner {
        width: 150px;
        height: 100px;
        background: orange;
        position: absolute;
        top: 50%;
        margin: -50px 0 0 0;
    }
</style>

<div id="box">
    <div id="inner">
        <span>1. 使用绝对定位和负外边距对块级元素进行垂直居中</span>
    </div>
</div>

CSS 垂直居中方式

  1. 使用绝对定位和transform
<style>
    #box {
        width: 300px;
        height: 300px;
        background: #ddd;
        position: relative;
    }

    #inner {
        width: 150px;
        height: 100px;
        background: orange;
        position: absolute;
        top: 50%;
        transform: translate(0, -50%);
    }
</style>

<div id="box">
    <div id="inner">
        <span>使用绝对定位和transform</span>
    </div>
</div>

CSS 垂直居中方式

  1. 绝对定位结合margin: auto
<style>
    #box {
        width: 300px;
        height: 300px;
        background: #ddd;
        position: relative;
    }

    #inner {
        top: 0;
        bottom: 0;
        width: 150px;
        height: 100px;
        background: orange;
        position: absolute;
        margin: auto 0;
    }
</style>

<div id="box">
    <div id="inner">
        <span>绝对定位结合margin: auto</span>
    </div>
</div>

CSS 垂直居中方式

  1. 使用flex布局
<style>
    #box {
        width: 300px;
        height: 300px;
        background: #ddd;
        display: flex;
        align-items: center;
    }

    #inner {
        width: 150px;
        height: 100px;
        background: orange;
    }
</style>

<div id="box">
    <div id="inner">
        <span>使用flex布局</span>
    </div>
</div>

CSS 垂直居中方式

  1. 使用flex布局 方式二
<style>
    #box {
        width: 300px;
        height: 300px;
        background: #ddd;
        display: flex;
        flex-direction: column;
        justify-content: center;
    }

    #inner {
        width: 150px;
        height: 100px;
        background: orange;
    }
</style>

<div id="box">
    <div id="inner">
        <span>使用flex布局 方式二</span>
    </div>
</div>

CSS 垂直居中方式

相关文章:

  • 2021-11-24
  • 2022-12-23
猜你喜欢
  • 2021-12-04
  • 2021-10-09
  • 2022-02-17
  • 2021-12-04
  • 2021-04-23
  • 2021-08-05
  • 2021-06-08
相关资源
相似解决方案