居中布局
一、水平居中(子元素)
【1】.常规元素设置水平居中:
《1》行内元素、不定宽块级元素:设置父元素 text-align:center
<div class="outer">
<div class="inner">水平居中的元素</div>
</div>
.outer {
border: 1px red solid;
height: 100px;
width: 500px;
text-align: center;
}
《2》定宽块级元素:设置子元素: margin:0 auto;
.outer {
border: 1px red solid;
height: 100px;
width: 500px;
text-align: center;
}
.inner {
/* 文字水平居中 要不文字靠左 */
text-align: center;
margin: 0 auto;
background: red;
width: 200px;
}
《3》图片水平居中:设置img clear+display+margin
<div class="outer">
<img src="1.jpeg" />
</div>
.outer {
border: 1px red solid;
height: 700px;
width: 1000px;
text-align: center;
}
img {
clear: both;
display: block;
margin: 0 auto;
}
《4》通用方法(不管行/块级元素):
设置父元素 display:flex; justify-content(水平对齐方式):center;
.outer {
border: 1px red solid;
height: 100px;
width: 500px;
display: flex;
justify-content: center;
}
.inner {
/* 文字水平居中 要不文字靠左 */
text-align: center;
margin: 0 auto;
background: red;
/* 不设置高度 会填充高度 */
height: 50px;
width: 200px;
}
二、垂直居中(垂直居中,默认外部元素(这里称为父元素)是有高度的)
【1】常规元素的垂直居中
《1》行内元素,设置 子元素 line-height=父元素height
.outer {
border: 1px red solid;
height: 40px;
width: 500px;
}
.inner {
/* line-height高度和父元素高度一样 */
line-height: 40px;
height: 30px;
background: cornflowerblue;
}
《2》通用(行/块/图片) 设置父:dispaly:table-cell + vertical-align:middle
或者父: display:flex + align-items(垂直方向的对齐):center
.outer {
border: 1px red solid;
height: 40px;
width: 500px;
/* 设置父:dispaly:table-cell + vertical-align:middle */
display: table-cell;
vertical-align: middle;
}
.inner {
line-height: 40px;
height: 40px;
background: rgb(38, 190, 157);
}
.outer {
border: 1px red solid;
height: 80px;
width: 500px;
/* display:flex + align-items(垂直方向的对齐):center */
display: flex;
align-items: center;
}
.inner {
line-height: 40px;
height: 40px;
background: rgb(38, 190, 157);
}
三、水平垂直居中
《1》table通用(一列或多列)
父元素设置 display: table-cell + vertical-align:middle + text-align:center
.outer {
border: 1px red solid;
height: 80px;
width: 500px;
/* 设置父:dispaly:table-cell + vertical-align:middle */
display: table-cell;
vertical-align: middle;
text-align: center;
}
.inner {
line-height: 40px;
height: 40px;
background: rgb(38, 190, 157);
}
《2》水平垂直通用(常规/浮动/绝对定位): flex
.outer {
border: 1px red solid;
height: 80px;
width: 500px;
display: flex;
align-items: center;
justify-content: center;
}
.inner {
line-height: 40px;
height: 40px;
background: rgb(38, 190, 157);
}
四、绝对定位和相对定位问题(引用外部图片)