行内元素的居中

水平居中
  • text-align:center;
<body>
    <div class="parent"> 
           <span class="child">content</span>
    </div>
</body>
<style>
    .parent{
        background-color: red;
        text-align: center;
    }
</style>

image

  • fit-content;
<body>
    <div class="parent"> 
           <span class="child">content</span>
    </div>
</body>
<style>
    .parent{
        background-color: red;
        width: fit-content;/*父元素适应子元素的宽度*/
        margin: auto;
    }
</style>

image

垂直居中
  • line-height;(只针对单行文本)
<body>
    <div class="parent"> 
           <span class="child">content</span>
    </div>
</body>
<style>
    .parent{
        background-color: red;
        height: 200px;
        line-height: 200px;
    }
</style>

image


块级元素的居中

水平居中

* margin:0 auto;

<body>
    <div class="parent"> 
           <div class="child">content</div>
    </div>
</body>
<style>
    .parent{
        background-color: red;
    }
    .child{
        background-color: blue;
        width: 100px;
        margin: 0 auto;/*左右自适应*/
    }
</style>

水平垂直居中

  1. 定位
<body>
    <div class="parent"> 
           <div class="child"></div>
    </div>
</body>
<style>
    .parent{
        background-color: red;
        position: relative;
        height: 200px;
    }
    .child{
        background-color: blue;
        width: 100px;
       height: 100px;
       position: absolute;
       left: 50%;
       top: 50%;
       margin-top: -50px;
       margin-left: -50px;
    }
</style>

2.定位+transform

<body>
    <div class="parent"> 
           <div class="child"></div>
    </div>
</body>
<style>
    .parent{
        background-color: red;
        position: relative;
        height: 200px;
    }
    .child{
       background-color: blue;
       position: absolute;
       left: 50%;
       top: 50%;
       transform: translate(-50%,-50%);
       /*子元素大小未知*/
    }
</style>

3.定位+margin

<body>
    <div class="parent"> 
           <div class="child"></div>
    </div>
</body>
<style>
    .parent{
        background-color: red;
        position: relative;
        height: 200px;
    }
    .child{
        background-color: blue;
        width: 100px;
        height: 100px;
        position: absolute;
        margin: auto;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
    }
</style>

4.padding

<body>
    <div class="parent"> 
           <div class="child"></div>
    </div>
</body>
<style>
    .parent{
        padding: 20px;
        background-color: red;
    }
    .child{
        height: 200px;
        background-color: blue;
    }
</style>

5.flex

<body>
    <div class="parent"> 
           <div class="child"></div>
    </div>
</body>
<style>
    .parent{
        display: flex;
        height: 200px;
        align-items: center;
        justify-content: center;
        background-color: red;
    }
    .child{
        height: 100px;
        width: 100px;
        background-color: blue;
    }
</style>

6.伪元素
7.函数calc


中二病の软
148 声望7 粉丝