Css元素水平居中,垂直居中方法彙總

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Css元素水平居中,垂直居中方法彙總</title>
</head>
<style>
    .div1{width: 200px;height: 200px;border:1px solid #ccc}
    .div2{width: 150px;height: 150px;background: #139acc;}
    .div3{width:200px;height:200px;background: #dad4cd;}

    .text-center{text-align:center}
    .text-h-v-center{text-align:center;line-height: 200px}
    .img-h-v-center{text-align:center;display: table-cell;vertical-align: middle;}
    .div-h-center{display: table-cell;vertical-align: middle;}
    .div-v-center{margin:0 auto}

    .box {  position: relative;  }
    .content1 {  position: absolute;  left: 50%;  top: 50%;  margin: -75px 0 0 -75px;  }
    .content2 {  position: absolute;  left: 50%;  top: 50%;  transform: translate(-50%,-50%);  }
    .box1 {  display: flex;/*flex佈局*/  justify-content: center;/*使子項目水平居中*/  align-items: center;/*使子項目垂直居中*/  }

    .main{  text-align: center; /*讓div內部文字居中*/
        background-color: #bda5ff;  border-radius: 20px;  width: 350px;  height: 250px;
        margin: auto;  position: absolute;  top: 0;  left: 0;  right: 0;  bottom: 0;  }

    .main1{
        text-align: center;  background-color: rgba(204, 29, 36, 0.34);  border-radius: 20px;
        width:250px;height:150px;  position: absolute;  left: 50%;  top: 50%;  transform: translate(-50%,-50%);  }
</style>
<body>

<h3 class="text-center">Css元素水平垂直居中方法彙總</h3>

<h4>1.文字居中</h4>
<div class="div1">
    <div class="text-h-v-center">我要居中</div>
</div>

<h4>2.圖片居中</h4>
<div class="div1 img-h-v-center">
    <img src="img/icon03.png"/>
</div>
<h4>3.無定位情況下-實現居中</h4>
<div class="div1 div-h-center">
    <div class="div2 div-v-center"></div>
</div>

<h4>4.相對定位,絕對定位-實現居中</h4>
<div class="div1 box">
    <div class="div2 content1">
    </div>
</div>

<h4>5.相對定位,絕對定位-實現居中(transform: translate(-50%,-50%))</h4>
<div class="div1 box">
    <div class="div2 content2">
    </div>
</div>

<h4>6.flex佈局-實現居中</h4>
<div class="div1 box1">
    <div class="div2">
    </div>
</div>

<h4>7.屏幕水平垂直居中</h4>
<div class="main">
    <div class="main1">
        <img src="img/icon03.png">
        <p>我想居中</p>
    </div>
</div>

</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章