(一)文本居中
<body>
<div>
<p>這是文本居中</p>
</div>
</body>
1、文本水平居中:
text-align: center;
2、文本垂直居中:
line-height: "容器高度";
3、代碼、截圖:
div{
width: 300px;
height: 200px;
background-color: red;
/* 文本水平居中 */
text-align: center;
/* 文本垂直居中 */
line-height: 200px;
}
(二)盒子居中
<body>
<div id="parent">
<p>這是父盒子</p>
<div id="son">
<p>這是子盒子</p>
</div>
</div>
</body>
1、盒子水平居中:
自動調整左右的外邊距margin來實現水平居中,當然需要注意的是子盒子是有寬度的
#parent{
width: 600px;
height: 400px;
background-color: blue;
}
#son{
width: 300px;
height: 200px;
background-color: red;
/* 盒子水平居中 */
margin: 0 auto;
}
2、盒子水平、垂直居中:
1、首先父盒子要先相對定位,然後子盒子再絕對定位,如果父盒子不相對定位,那麼子盒子的絕對定位就會脫離父盒子定位;
2、子盒子的絕對定位是以左上角爲原點移動的,所以left: 50% 和 top: 50% 只是根據左上角爲原點來居中的,而沒有使子盒子中心整體居中;
3、所以需要分別縮小外邊距margin-left和margin-top到子盒子寬度和高度的一半,也就相當於原點移動到了子盒子正中心;
#parent{
width: 600px;
height: 400px;
background-color: blue;
/* 父盒子相對定位 */
position: relative;
}
#son{
width: 300px;
height: 200px;
background-color: red;
/* 子盒子絕對定位*/
position: absolute;
/* 水平居中 */
left: 50%;
margin-left: -150px;/* -(子盒子寬度)/2 */
/* 垂直居中 */
top: 50%;
margin-top: -100px;/* -(子盒子高度)/2 */
}
3、盒子水平、垂直居中:
定位和方法2一樣, 而translate(-50%,-50%) 作用是,往上(x軸),左(y軸)移動自身長寬的 50%,以使其居於中心位置。
#parent{
width: 600px;
height: 400px;
background-color: blue;
/* 父盒子相對定位 */
position: relative;
}
#son{
width: 300px;
height: 200px;
background-color: red;
/* 子盒子絕對定位*/
position: absolute;
/* 水平垂直居中 */
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
4、盒子水平、垂直居中:
<font color=“green”/1、這種辦法是使父元素內的子元素橫向排列,然後分別水平和垂直居中
2、需要注意的是如果父盒子內有多個元素,那麼將根據這多個元素橫向排列的總寬度的中心來居中,如果想要垂直排列,我們可以加上
3、例如本實例中父盒子中就有兩個元素,一個段落p和一個盒子div,分爲橫向排列和垂直居中效果,如圖:
#parent{
width: 600px;
height: 400px;
background-color: blue;
/* 父盒子內元素橫向排列 */
display: flex;
/* 水平居中 */
justify-content: center;
/* 垂直居中 */
align-items: center;
}
#son{
width: 300px;
height: 200px;
background-color: red;
}
#parent{
width: 600px;
height: 400px;
background-color: blue;
/* 父盒子內元素橫向排列 */
display: flex;
/* 垂直排列方向 */
flex-direction: column;
/* 水平居中 */
justify-content: center;
/* 垂直居中 */
align-items: center;
}
#son{
width: 300px;
height: 200px;
background-color: red;
}
(三)浮動居中
。。。