一、水平居中div
給div設置一個寬度,然後添加margin:0 auto屬性
div{
width:600px;
margin:0 auto;
}
width
可以阻止它從左到右撐滿容器。然後你就可以設置左右外邊距爲 auto
來使其水平居中。元素會佔據你所指定的寬度,然後剩餘的寬度會一分爲二成爲左右外邊距。
不過,當瀏覽器窗口比元素的寬度還要窄時,瀏覽器會顯示一個水平滾動條來容納頁面。
div {
max-width: 600px;
margin: 0 auto;
}
在這種情況下使用 max-width
替代 width
可以使瀏覽器更好地處理小窗口的情況。
二、水平垂直居中
法1、
.align-center{
position: absolute;
left: 50%;
top: 50%;
width: 400px;
height: 400px;
margin-top: -200px;
margin-left: -200px;
border:1px dashed #333;
}
負邊距+定位:水平垂直居中,使用絕對定位將content的定點定位到body的中心,然後使用負margin(content寬高的一半),將content的中心拉回到body的中心,已達到水平垂直居中的效果
法2、
#content {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
height: 200px;
width: 200px;
background: red;
}
這個方法使用了一個 position:absolute
,有固定寬度和高度的 div
。這個 div
被設置爲 top:0;
bottom:0;
。但是因爲它有固定高度,其實並不能和上下都間距爲 0,因此 margin:auto;
會使它居中。這裏就是使用 margin:auto;
使塊級元素垂直居中。
法3、
利用相對定位:
.main{
width: 300px;
height: 300px;
margin:-150px 0 0 -150px;
position: relative;
background: red;
top:50%;
left: 50%;
}
但會出現一個問題:
在嘗試把.main這個父元素在瀏覽器居中顯示時發現,如果設定position:relative;
top屬性值以百分號(percentage)爲單位時,會失效。此時元素會貼在瀏覽器;
而left以百分號爲單位卻能正常顯示
如果設定position:absolute;百分號爲單位可以正常顯示。如法2
經查證經驗需添加父元素寬高
.container{
width: 500px;
height: 500px;
background: #ccc;
}
.main{
width: 300px;
height: 300px;
margin:-150px 0 0 -150px;
position: relative;
background: red;
top:50%;
left: 50%;
}
問題也並沒有得到解決。。。
三、如何居中一個浮動元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.p{
position: relative;
left: 50%;
float: left;
}
.c{
position: relative;//相對於自身定位
float: left;
right: 50%;
}
</style>
</head>
<body>
<div class="p">
<div class="c">Test Float Element Center</div>
</div>
</body>
</html>
原理:父元素和子元素同時左浮動,然後父元素相對左移動50%,子元素相對右移動50%,或者子元素相對左移動-50%
四、三欄佈局,中間自適應
法1、自身浮動法。左邊左浮動,右邊右浮動
.left .right{
height: 300px;
width: 200px;
}
.right{
float: right;
background: red;
}
.left{
float: left;
background: #ccc;
}
.middle{
height: 300px;
margin:0 200px;
background: blue;
}
法2、margin負值法
.left .right{
height: 300px;
width: 200px;
float: left;
}
.right{
margin-left: -200px;
background: red;
}
.left{
margin-left: -100px;
background: #ccc;
}
.middle{
height: 300px;
width: 100%;
float: left;
background: blue;
}
middle放第一行:
<div class="middle"></div>
<div class="left"></div>
<div class="right"></div>
法3、絕對定位法。左右兩欄採用絕對定位,分別固定於頁面的左右兩側,中間的主體欄用左右margin值撐開距離
.left .right{
top:0;
height: 300px;
width: 200px;
position: absolute;
}
.right{
right: 0;
background: red;
}
.left{
left: 0;
background: #ccc;
}
.middle{
margin:0 200px;
height: 300px;
background: blue;
}