css實現元素水平垂直置中常見的兩種方式執行個體詳解

來源:互聯網
上載者:User
這篇文章主要給大家介紹了css實現元素水平垂直置中的兩種方式,文中給出了完整的範例程式碼供大家參考學習,對大家的學習或者工作具有一定的參考價值,有需要的朋友們下面來一起看看吧。

一、父元素的flex布局實現元素的水平垂直置中

範例程式碼如下:


<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport" content="width=device-width, initial-scale=1.0">  <meta http-equiv="X-UA-Compatible" content="ie=edge">  <title>Document</title>  <style>    .parent{      display:flex;      display:-webkit-flex;      justify-content: center;      align-items: center;      width:100%;      height: 200px;      background-color: #c43;    }    .child{      width:300px;      height:100px;      background-color: #c4235b;    }  </style></head><body>  <p class="parent">    <p class="child"></p>  </p></body></html>

如下:

二、絕對位置&負margin值實現元素水平垂直置中

注意:元素本身需要確定寬度和高度

範例程式碼如下:


<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport" content="width=device-width, initial-scale=1.0">  <meta http-equiv="X-UA-Compatible" content="ie=edge">  <title>Document</title>  <style>    p{      width:300px;      height:100px;      background-color: #873cac;      position:absolute;      top:50%;      left:50%;      margin-left: -150px;      margin-top:-50px;    }    </style></head><body>  <p></p></body></html>

如下:

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.