1、水平居中
width: 100px;
margin: 0 auto;
如果是字體的話,最好的居中方式text-align: center
2、水平垂直居中
- 不知道容器的寬高,這也是最常用的一種方法
<div id="app">
<div class="global"></div>
</div>
#app {
position: fixed或者absolute; // 總之要脫離普通的文檔流,fixed就是瀏覽器的窗口大小
top: 0;
right: 0;
bottom: 0;
left: 0;
background: pink;
height: 100%;
width: 100%; // 必須寫上
}
.global {
position: absolute;(絕對定位、相對定位都可以)
width: 100px;
height: 100px;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background: yellow;
}
- 知道容器的寬高
<div id="app">
<div class="global"></div>
</div>
#app {
position: fixed或者absolute; // 總之要脫離普通的文檔流
width: 100%;
height: 500px;
background: pink;
}
.global {
position: absolute;(絕對定位、相對定位都可以)
width: 100px;
height: 100px;
left: 50%;
top: 50%;
// transform: translate(-50%, -50%);
margin: -50px 0 0 -50px; // 邊距設(shè)置為寬高的負一半值
}
- flex布局,使用非常方便,但要注意兼容性,在IE上有很大的問題
<div id="app">
<div class="global"></div>
</div>
#app {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 500px;
background: pink;
}
.global {
width: 100px;
height: 100px;
background: yellow;
}
為整張頁面設(shè)置背景色有兩種方式
1、在根元素html當(dāng)中設(shè)置,這種方法有一弊端,整個項目都會有所設(shè)置的屬性
2、在最外層的div中設(shè)置,但會產(chǎn)生一個問題,background不會占滿整個屏幕,因為每個瀏覽器都有默認的
margin值,要解決這個問題,就是在body中,把margin的值重置為0
總結(jié):
1、普通文檔流(normal flow)默認width: auto; height: auto,width默認會與瀏覽器的窗口對齊,因為高
度是可以無限延長的,所以把height: 100%這樣設(shè)置并不管用,必須給html、body也加上這個屬性才管用。
2、當(dāng)position: absolute(fixed),此時已經(jīng)脫離普通文檔流了,也意味著沒有width: auto;
height: auto默認屬性了,所以width、height都隨自己設(shè)置,如果要滿屏的話,
width: 100%; height: 100%