前言:给你一个div,宽高400px,在这个div中居中一个div,宽高200px,你有几种方法。
- 设置padding值来实现
<style>
.outer{
width: 400px;
background: #000;
padding: 100px;
}
.inner{
height: 200px;
width: 200px;
background: #fff;
}
</style>
<body>
<div class='outer'>
<div class='inner'></div>
</div>
</body>
其中,设置padding值,父元素不用设置高度,除非高度正好是内边距和子元素高之和,例如在这个例子中outer
的height:200px
则满足条件。但是这个方法很局限,宽度和padding值都需要计算。
2. 利用margin和定位的方法
设置left和top为50%,元素在右下方,再通过margin将元素回拉它本身高宽的一半值,将其拉到中间。
<style type="text/css">
*{margin:0; padding: 0;}
.outer{
width: 400px;
height: 400px;
background: #000;
position: relative;
}
.inner{
position: absolute;
width: 200px;
height: 200px;
left: 50%;
top: 50%;
background-color: #fff;
margin: -100px;
}
</style>
3 . 设置margin
和top
、bottom
、right
、left
<style type="text/css">
*{margin:0; padding: 0;}
.outer{
position: relative;
width: 400px;
height: 400px;
background: #000;
}
.inner{
position: absolute;
width: 200px;
height: 200px;
margin:auto;
top: 0;
bottom: 0;
right:0;
left:0;
background: #fff;
}
</style>
<body>
<div class='outer'>
<div class='inner'>
</div>
</div>
</body>
效果如上图。此方法不知道inner元素的宽高也可以使用。
首先margin
的auto
属性的作用是用来分配剩余空间,所以对于有剩余空间的元素才有效(块及元素)。
当left、right、bottom、top都为0时,margin:auto
还未写入时,子元素宽高未定,则自动填充了整个父元素。当设置了宽高,原本应该填充的空间就被多余了出来,这多余的空间就是margin:auto计算的空间。如图:
这个时候添加margin:auto
,则水平和垂直方向同时居中了。因为,auto正好把上下左右剩余空间全部等分了水平和垂直方向同时居中了。不过此方法不适合IE6/7。
margin:auto实现绝对定位元素的水平垂直居中
4. 通过flex布局实现
<style type="text/css">
*{margin:0; padding: 0;}
.outer{
width: 400px;
height: 400px;
background: #000;
display: flex;
display: -webkit-flex;//Safari仍旧需要使用特定的浏览器前缀
justify-content:center;
align-items:center;
}
.inner{
width: 200px;
height: 200px;
background-color: #fff;
}
</style>
<body>
<div class='outer'>
<div class='inner'>
</div>
</div>
</body>
5.transform
通过设置left和top为50%,通过transform的translate移动到中间位置。
<style type="text/css">
*{margin:0; padding: 0;}
.outer{
position: relative;
width: 400px;
height: 400px;
background: #000;
}
.inner{
position: absolute;
height: 200px;
width: 200px;
left: 50%;
top: 50%;
background: #fff;
transform:translate(-50%,-50%);
}
</style>
新手博客,请多多指教,如果有不对的地方,希望大家可以指正ヽ(・ω・´メ)