最近寫網頁經常需要將div在屏幕中居中顯示,遂記錄下幾個常用的方法,都比較簡單。
水平居中直接加上<center>
標簽即可,或者設置margin:auto;
當然也可以用下面的方法
下面說兩種在屏幕正中(水平居中+垂直居中)的方法
放上示范的html代碼:
<body> <div class="main"> <h1>MAIN</h1> </div> </body>
- 1
- 2
- 3
- 4
- 5
- 方法一:
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; }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
效果如圖:
- 方法二:
仍然是絕對布局,讓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%); }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11