作为个渣渣实习生,一路懵懵懂懂的过了实习期,然而还是懵懂,很多东西理解的不是很透彻,现在把自己收藏的一些css文章(自己觉得是挺有用的)整理出来,都是一些基础!
1、水平居中
text-align:center; margin:0 auto;(同时还要设置宽度,否则看不出效果的)
多个块级元素:适应一个不同的display类型(在线示例: http://jsfiddle.net/ourjs/0b6b7wt8/)
html:
<main class="inline-block-center">
<div>
I'm an element that is block-like with my siblings and we're centered in a row.
</div>
<div>
I'm an element that is block-like with my siblings and we're centered in a row. I have more content in me than my siblings do.
</div>
<div>
I'm an element that is block-like with my siblings and we're centered in a row.
</div>
</main>
<main class="flex-center">
<div>
I'm an element that is block-like with my siblings and we're centered in a row.
</div>
<div>
I'm an element that is block-like with my siblings and we're centered in a row. I have more content in me than my siblings do.
</div>
<div>
I'm an element that is block-like with my siblings and we're centered in a row.
</div>
</main>
css:
body {
background: #f06d06;
font-size: 80%;
}
main {
background: white;
margin: 20px 0;
padding: 10px;
}
main div {
background: black;
color: white;
padding: 15px;
max-width: 125px;
margin: 5px;
}
.inline-block-center {
text-align: center;
}
.inline-block-center div {
display: inline-block;
text-align: left;
}
.flex-center {
display: flex;
justify-content: center;
}
2、垂直居中
2-1设置上下padding相等,在这个不能用且文本不会换行的情况下,使用line-heigth(文本为一行)
2-2、上下等padding的方式可以让多行居中,如果没用,可以让文字的容器按table cell模式显示,设置文字的vertical-align属性对齐,就像talbe那样(在线演示: http://jsfiddle.net/ourjs/0fn2u4rc/)
2-3、在高度固定时,用绝对定位,top: 50%;margin-top: -50px(在没有使用border-box的盒子模型需要设置这个);
未知高度(在线演示: http://jsfiddle.net/ourjs/9sLf7p56/)
2-4、使用flexbox
html:
<main>
<div>
I'm a block-level element with an unknown height, centered vertically within my parent.
</div>
</main>
css:
body {
background: #f06d06;
font-size: 80%;
}
main {
background: white;
height: 300px;
width: 200px;
padding: 20px;
margin: 20px;
display: flex;
flex-direction: column;
justify-content: center;
resize: vertical;
overflow: auto;
}
main div {
background: black;
color: white;
padding: 20px;
resize: vertical;
overflow: auto;
}
3、同时水平、垂直居中
3-1、元素有固定宽高
position: absolute;top: 50%;left: 50%;
3-2、宽高未知
position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);
3-3、
margin:auto;position:absolute;top:0;left:0;bottom:0;right:0(相对居中的父级要加上relative)