css实现居中对齐的几种方式

一般来说居中的话可分为水平居中与垂直居中,以下是我个人总结的几种方式

1.水平居中:

  • inline元素:text-algin:center实现
  • block元素:margin:auto
  • absolute元素:left:50%+margin-left:负该盒子宽度的一半(必须得知道该元素的宽度)

2.垂直居中

  • inline元素:line-height=height实现
  • absolute元素:left:50%+margin-top:负该盒子高度的一半(必须得知道该元素的高度)
  • absolute元素:transform(-50%,-50%)
  • absolute元素:left,right,top。bottom都等于0加上margin:auto

具体实现代码如下:

<body>
    <div class="container container-1">
        <span>一段文字</span>
    </div>

    <div class="container container-2">
        <div class="item">
            this is item
        </div>
    </div>

    <div class="container container-3">
        <div class="item">
            this is item
        </div>
    </div>

    <div class="container container-4">
        <div class="item">
            this is item
        </div>
    </div>
</body>
<style type="text/css">
        .container {
            border: 1px solid #ccc;
            margin: 10px;
            padding: 10px;
            height: 200px;
        }
        
        .item {
            background-color: #ccc;
        }
        
        .container-1 {
            text-align: center;
            line-height: 200px;
            height: 200px;
        }
        
        .container-2 {
            position: relative;
        }
        
        .container-2 .item {
            width: 300px;
            height: 100px;
            position: absolute;
            left: 50%;
            margin-left: -150px;
            top: 50%;
            margin-top: -50px;
        }
        
        .container-3 {
            position: relative;
        }
        
        .container-3 .item {
            width: 200px;
            height: 80px;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%)
        }
        
        .container-4 {
            position: relative;
        }
        
        .container-4 .item {
            width: 100px;
            height: 50px;
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            margin: auto;
        }
    </style>

 

posted @ 2021-08-29 20:50  小吴3  阅读(1206)  评论(0编辑  收藏  举报