1、内联元素在父元素内居中显示
常见内联元素:
a、abbr、acronym、b、bdo、big、br、cite、code、dfn、em、font、i、img、input、kbd、label、q、s、samp、select、small、span、strike、strong、sub、sup、textarea、tt、u、var……
• 情境①:父元素未设置尺寸
<div class="parent" style="background:lightgray;">
<span class="child">我是内联元素</span>
</div>
/* 给父元素添加样式 */
.parent {
text-align: center; /* 水平居中 */
}
• 情境②:父元素已设置宽高
<div class="parent" style="background:lightgray; width:300px; height:100px;">
<span class="child">我是内联元素</span>
</div>
/* 给父元素添加样式 */
.parent {
text-align: center; /* 水平居中,不受宽度值影响 */
line-height: 100px; /* 垂直居中,line-height需与height一样高 */
/* 若还设置边距,需左右相等、上下相等 */
}
2、块级元素在父元素内居中显示
常见块级元素:
address、blockquote、center、dir、div、dl、fieldset、form、h1~h6、hr、isindex、menu、noframes、noscript、ol、p、pre、table、ul……
• 情境①:父元素及该元素都未设置尺寸
<div class="parent" style="background:lightgray;">
<p class="child">我是块级元素</p>
</div>
/* 给父元素添加样式 */
.parent {
text-align: center; /* 水平居中 */
}
• 情境②:父元素未设置尺寸,但该元素已设置宽高
<div class="parent" style="background:lightgray;">
<p class="child" style="width:300px; height:100px; background:grey;">我是块级元素</p>
</div>
/* 给该元素添加样式 */
.child {
margin: auto; /* 水平居中 */
}
• 情境③:父元素已设置宽高,但该元素未设置尺寸
<div style="width:450px; height:150px; background:ghostwhite;">
<div class="parent" style="width:300px; height:100px; background:lightgray;">
<p class="child">我是块级元素</p>
</div>
</div>
/* 先给该元素添加样式 */
.child {
display: inline-block; /* 转换为行内块元素,而且可继续设置宽高 */
}
/* 再给父元素添加样式,相当于内联元素方法 */
.parent {
text-align: center;
line-height: 100px;
}
• 情境④:父元素及该元素都已设置宽高
<div style="width:450px; height:150px; background:ghostwhite;">
<div class="parent" style="width:300px; height:100px; background:lightgray;">
<p class="child" style="width:100px; height:30px; background:grey;">我是块级元素</p>
</div>
</div>
/* 先给父元素添加样式 */
.parent {
position: absolute; /* position属性是必须的,定位方式视需求而定 */
/* top: 9px;
left: 21px; 偏移距离视需求而定,若不设置则父元素不动 */
}
/* 再给该元素添加样式 */
.child {
position: absolute; /* 相对父元素定位 */
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto; /* 水平垂直居中 */
/* margin: 0 auto; 仅水平居中 */
/* margin: auto 0; 仅垂直居中 */
}