1. 程式人生 > html教程 > HTML+CSS,讓div在螢幕中居中(水平居中+垂直居中)方法總結

HTML+CSS,讓div在螢幕中居中(水平居中+垂直居中)方法總結

最近寫網頁經常需要將div在螢幕中居中顯示,遂記錄下幾個常用的方法,都比較簡單。
水平居中直接加上<center>標籤即可,或者設定margin:auto;當然也可以用下面的方法

下面說兩種在螢幕正中(水平居中+垂直居中)的方法
放上示範的html程式碼:

<body> <div class="main"> <h1>MAIN</h1> </div></body>
  • 方法一:

div使用絕對佈局,設定margin:auto;並設定top、left、right、bottom的值相等即可,不一定要都是0。

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

效果如圖:
HTML+CSS,讓div在螢幕中居中(水平居中+垂直居中)方法總結_HTML/CSS

  • 方法二:
    仍然是絕對佈局,讓left和top都是50%,這在水平方向上讓div的最左與螢幕的最左相距50%,垂直方向上一樣,所以再用transform向左(上)平移它自己寬度(高度)的50%,也就達到居中效果了,效果圖和上方相同。
.main{ text-align: center; background-color: #fff; border-radius: 20px; width: 300px; height: 350px; position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%);}




有不懂的地方歡迎加我QQ,點這裡加好友 一起討論——YinyouPoet