CSS Tricks
一些CSS的小技巧
1.如何准确的居中?
参考Quick CSS Trick: How To Center an Object Exactly In The Center
.centered {
position: fixed;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -100px;
}
2.铺满背景的图片
参考Perfect Full Page Background Image,有多种方式
例如,使用background-size: cover
:
html {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
3.display:block/inline-block时的居中
参考How to center things - display:block/inline-block
margin:0 auto;
一般用于块级元素的居中
而对于display: inline
,居中的唯一方式是:在父级元素上指定text-align: center
display: inline-block
可以一个接一个的显示元素,也可以利用display: block
的一些有用的东西,例如,最常用的就是HEIGHT
4.div中inline-block元素的垂直居中
参考Align inline-blocks with vertical-align,多种方式
如使用伪类:
<h3>With an added pseudo element it's possible</h3>
<div class="block2">
<div class="inner">Inline-Block</div>
<div class="inner">Inline-Block</div>
</div>
/* With an added fake (pseudo) element it works. IMPORTANT: There must be no spaces between the elements in the source, else it doesn't work! */
.block2 {
background: orange;
height: 80px;
}
.inner {
display: inline-block;
vertical-align: middle;
background: yellow;
padding: 3px 5px;
}
/* Fake (pseudo) element, that enables vertical-align */
.block2:before {
content: "";
display: inline-block;
vertical-align: middle;
height: 100%;
}
5.div中一个div垂直对齐
参考Vertically centering a div inside another div
HTML
<div class="cn"><div class="inner">your content</div></div>
a.父元素使用table-cell
,子元素使用inline-block
.cn {
display: table-cell;
width: 500px;
height: 500px;
vertical-align: middle;
text-align: center;
}
.inner {
display: inline-block;
width: 200px; height: 200px;
}
效果如下:
b.更现代的方式,使用transform
.cn {
position: relative;
width: 500px;
height: 500px;
border: 1px solid red;
}
.inner {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%,-50%);
width: 200px;
height: 200px;
border: 1px solid blue;
}
c.使用flexbox
.cn {
display: flex;
justify-content: center;
align-items: center;
}