天天看點

php中div居中css,css中div垂直居中的方法。

利用絕對定位實作的居中

代碼如下:

居中

*{

padding: 0px;

margin: 0px;

}

body {

height: 100%;

overflow: hidden;

}

.father{

position: absolute;

height: 500px;

width: 100%;

background-color:#2AABD2;

}

.children{

position: absolute;

top: 50%;

left: 50%;

background-color: red;

width: 100px;

height: 100px;

margin: -50px 0 0 -50px;

}

效果圖如下:

php中div居中css,css中div垂直居中的方法。

利用flex垂直居中

居中

*{

padding: 0px;

margin: 0px;

}

body {

height: 100%;

overflow: hidden;

}

.father{

height: 500px;

width: 100%;

background-color:#2AABD2;

display: flex;

justify-content: center;

align-items:center;

}

.children{

background-color: red;

width: 100px;

height: 100px;

}

效果圖如下:

php中div居中css,css中div垂直居中的方法。

transform+relative實作的居中

居中

*{

padding: 0px;

margin: 0px;

}

body {

height: 100%;

overflow: hidden;

}

.father{

position: absolute;

height: 500px;

width: 100%;

background-color:#2AABD2;

}

.children

{

width: 300px;

height: 150px;

background-color: #333333;

position: relative;

top: 50%;

left: 50%;

transform: translateX(-50%) translateY(-50%);

}

效果圖如下:

php中div居中css,css中div垂直居中的方法。

多謝@alexxxcs1提供的另一種方式(不曉得這樣能否@到^_^),嘛其實網上實作居中的方式确實很多,互相探讨加深印象。