一、水平居中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;
}