1.垂直居中(方法一)
.wrap h2 {
margin:0;
height:100px;
line-height:100px;
background:#ccc;
}
<div class="wrap">
<h2>Hello world</h2>
</div>
總結: line-height 設置垂直居中
行高,指代文本中,行與行之間的基線間的距離。
Line-height行高屬性,運用到對文字排版,實現上下排文字間隔距離,以及單排文字在一定高度情況上下垂直居中布局。
2.垂直居中(方法二)
#parent {
display: flex;
align-items: center;
/justify-content: center;/
/水平居中/
width: 200px;
height: 200px;
background: yellow;
}
<div id="parent">
這是一個盒子垂直居中
</div>
總結:彈性盒的
justify-content:center;//元素在橫軸的對齊方式
align-items:center;//元素在縱軸的對齊方式
-
vertical-align 設置圖片垂直居中(行內元素 方法三)
*{margin:0;padding:0;}
.parent{
margin-left: 100px;
margin-top: 100px;
width: 600px;
height: 400px;
border: 1px solid #ddd;
border-radius: 15px;
background-color: #fff;
box-shadow: 0 3px 18px rgba(0,0,0,.5);
text-align: center;
}
.child{
width: 0;
line-height: 400px;
}
img{
vertical-align: middle;
}
<div class="parent">
<img src="a21.png" alt="">
<span class="child"></span>
</div>
總結:vertical-align 屬性設置元素的垂直對齊方式。
4.定位的居中方法(1)
.father{
width: 200px;
height: 200px;
background: pink;
position: relative;
}
.son{
width: 100px;
height: 100px;
background: yellowgreen;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
<div class="father">
<div class="son"></div>
</div>
總結:首先我們要了解樣式中的這兩種定位;
absolute(絕對定位):將被賦予的對象從文檔流中拖出,使用left,right,top,bottom等屬性相對于最接近的一個最有定位設置的父級對象進行絕對定位,如果父級沒有進行定位屬性設置,則按照默認規則來設定(根據body左上角作為參考進行定位),同時絕對定位的對象可層疊。
relative(相對定位):對象不可重疊,使用left,right,top,bottom等屬性在正常的文檔流中進行定位,其對象不可以層疊。
5.水平居中行內元素居中(1)
.div1{
text-align:center;
}
<div class="div1">Hello world</div>
6.水平居中相對定位(2)
.wrap{
float:left;
position:relative;
left:50%;
clear:both;
}
.wrap-center{
background:#ccc;
position:relative;
left:-50%;
}
<div class="wrap">
<div class="wrap-center">Hello world</div>
</div>
總結: 通過給父元素設置 float,然后給父元素設置 position:relative 和 left:50%,
子元素設置 position:relative 和 left: -50% 來實現水平居中。
7.圖片水平居中
.tu img{
display: block;
margin:0 auto;
}
<div class="tu">
<img src="img/one.jpg" >
</div>
8.table布局居中方法(1)
.father{
width: 200px;
height: 200px;
background: pink;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.son{
display: inline-block;
width: 100px;
height: 100px;
background: yellowgreen;
}
<div class="father">
<div class="son"></div>
</div>
10.div絕對定位水平垂直居中【margin 負間距】
div{
width:200px;
height: 200px;
background:green;
position: absolute;
left:50%;
top:50%;
margin-left:-100px;
margin-top:-100px;
}
11、<div class="parent">
<div class="child">
111
</div>
</div>
.parent{
height: 140px;
background: red;
display: grid;
}
.child{
margin: auto;
}
用法:grid 給他父級元素
margin: auto 給他的子元素
12、 .div{
width: 200px;
height: 200px;
background: pink;
margin: auto;
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: 0;
}
<div class="div"></div>