css元素水平垂直居中

发布时间 2023-10-20 13:57:11作者: 三鸡

1、单行文字的处理

<html>
    <head>
        <style>
            /* 要点,设置行高和DIV的行高一行 */
            #div{
                background-color: antiquewhite;
                height: 100px;
                line-height: 100px;
                text-align: center;
            }
        </style>
    </head>
    <body>
        
    
    <div id="div"> 
        我要水平垂直居中
      </div>
    </body>
</html>

效果图:

2、图片和块元素垂直居中,使用绝对定位和transform

<html>
    <head>
        <style>
            #div{
                background-color: antiquewhite;
                height: 300px;
                position: relative;
               
            }
            .block{
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%,-50%);
                background-color: orange;
            }
        </style>
    </head>
    <body>
        
    
    <div id="div"> 
        <div class="block" >日子,要的是知足;生活,要的是幸福;生命,要的是健康;做人,要的是骨气;做事,要的是尽心;人生,要的是无悔。珍惜身边的幸福;欣赏自己的拥有。</div>
        <img src="./static/newyear/public/images/20.png"  class="block" >
      </div>
    </body>
</html>

效果图: