這篇文章主要給大家介紹了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>
如下: