Skip to content

Instantly share code, notes, and snippets.

@cycold
Created May 8, 2014 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cycold/1ac31bf6d1c01ac1cce0 to your computer and use it in GitHub Desktop.
Save cycold/1ac31bf6d1c01ac1cce0 to your computer and use it in GitHub Desktop.
.container{
width:95%;
height:200px;
background: #f90;
margin: 10px auto 0;
position: relative;
}
/*
这里将left, right设为0 那么如果设置margin左右auto,就会 和relative定位的margin左右auto居中效果一致
同理top,bottom设为0将会取得垂直居中
Tested in Google Chrome, Firefox, and IE8
*/
.box-1{
width:30%;
height:30%;
/* height:auto; */
background: green;
position: absolute;
text-align:center;
left:0;
right:0;
top:0;
bottom:0;
margin: auto auto;
}
/*
使用left:50%;然后再利用负的margin将其多余的部分拉回来
*/
.box-2{
width:100px;
height:100px;
background:green;
position:absolute;
text-align:center;
left:50%;
top:50%;
margin-left:-50px;
margin-top:-50px;
}
/*使用calc*/
.box-3{
width:30%;
height:30%;
background:green;
position:absolute;
text-align:center;
left: calc(50% - 15%); /*注意减号左右须有空格*/
top: calc(50% - 15%);
}
/*使用translate3d(不支持IE9) 但是tanslate支持IE9*/
.box-4{
width:30%;
height:30%;
background:green;
position:absolute;
text-align:center;
left: 50%;
top:50%;
/*transform还需要增加前缀*/
/*使用translate 2d的旋转*/
/* -webkit-transform: translate(-50%, -50%); */
/*或者如果不想支持IE9 可以使用3d的*/
-webkit-transform: translate3d(-50%,-50%,0);
-moz-transform: translate3d(-50%,-50%,0);
}
<meta name="description" content="绝对定位元素居中问题" />
<body>
<!--
参考文档:
http://stackoverflow.com/questions/16758102/how-do-i-horizontally-center-an-absolute-positioned-element-inside-a-100-width
http://stackoverflow.com/questions/1776915/how-to-center-absolute-element-in-div
-->
<!-- 水平垂直居中 居中元素宽高动态变化(比如百分比)-->
<div class="container">
<div class="box-1">
Lorem ipsum dolor sit amet
dolor sit amet
</div>
</div>
<!-- 水平垂直居中 居中元素宽高固定 -->
<div class="container">
<div class="box-2">
Lorem ipsum dolor sit amet
dolor sit amet
</div>
</div>
<!-- 水平垂直居中 居中元素宽高固定 使用css3的计算函数calc-->
<div class="container">
<div class="box-3">
Lorem ipsum dolor sit amet
dolor sit amet
</div>
</div>
<!-- 水平垂直居中 居中元素宽高固定 使用css3的translat3d-->
<div class="container">
<div class="box-4">
Lorem ipsum dolor sit amet
dolor sit amet
</div>
</div>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment