Skip to content

Instantly share code, notes, and snippets.

@bennyzhao
Last active December 21, 2015 20:29
Show Gist options
  • Save bennyzhao/6361670 to your computer and use it in GitHub Desktop.
Save bennyzhao/6361670 to your computer and use it in GitHub Desktop.
上下居中的几种方式
/**
* From:http://coding.smashingmagazine.com/2013/08/09/absolute-horizontal-vertical-centering-css/
*/
/** basic css
* @see Set margin -> 'auto',position -> absolute.
* And t,l,b,r to a defined value.
* .center{
* margin: auto;
* position: absolute;
* top: 0; left: 0; bottom: 0; right: 0;
* }
**/
/** widthout a container
*/
.Absolute-Center {
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}
/** width a container
* @note When (child.width > contanier.width) horizontal centering does't work.
* But when (child.height > contanier.height) vertical centering works correct.
*/
.Center-Container {
width:500px;
height:500px;
background-color:lightblue;
position: relative;
}
.Absolute-Center {
width: 300px;
height: 200px;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}
/** Also we can set Offset
*/
.Absolute-Center.is-Right {
left: auto; right: 20px;
text-align: right;
}
.Absolute-Center.is-Left {
right: auto; left: 20px;
text-align: left;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Absolute Horizontal And Vertical Centering In CSS use margin</title>
<link rel="stylesheet" type="text/css" href='centering.css'>
</head>
<body>
<!--使用绝对定位,然后把上下左右都设置成0最后margin:auto-->
<div class='Center-Container'>
<div class='Absolute-Center'></div>
</div>
</body>
</html>
.wrapper {
display: table;
width: 100%;
height: 300px;
background-color: rgba(164, 0, 0, 0.9);
}
.c {
display: table-cell;
text-align: center;
vertical-align: middle;
}
<!--table-cell法-->
<!--将父容器设置成display:table而需要居中的子元素设置成display:table-cell-->
<div class="wrapper">
<div class="c">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment