各种居中的实现
这里我们要讨论各种情况的居中,包括水平居中和竖直居中。包括块级元素和行级元素的居中。浮动元素的居中。
居中一个div元素和其中的内容
#block-center {
width: 200px;
height: 200px;
margin-left: auto;
margin-right: auto;
background-color: #00ffff;
}
I'm lovely block!
User text-center to make content center align
User text-center to make content center align
居中inline元素
#inline-center {
/*span就是行级元素,这里可以不用声明*/
display: inline;
color: red;
font-weight: bold;
}
This is a span element
* 以上是一个span元素放在一个div中,所以span作为div的内容,需要经text-center的class放在div里,同上例一样
让一个position:relative的元素居中
#relative-block-center {
width: 200px;
height: 200px;
position: relative;
/*margin一定要设置成宽的一半*/
margin: 0 0 0 -100px;
left: 50%;
background-color: #00ffff;
}
I'm a relative-block element.
让一个position:absolute的元素居中
#absolute-block-center {
width: 200px;
height: 200px;
position: absolute;
margin: 0 auto;
left: 0;
right: 0;
background-color: #00ffff;
}
I'm a absolute-block element.
Mouse on me, disappear
Mouse on me, disappear
补充:position的值以及作用
- static
- 默认值。没有定位,元素出现在正常的流中(忽略 top, bottom, left, right 或者 z-index 声明)。
- relative
- 生成相对定位的元素,相对于其正常位置进行定位。因此,"left:20" 会向元素的 LEFT 位置添加 20 像素。
- absolute
- 生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。
- fixed
- 生成绝对定位的元素,相对于浏览器窗口进行定位。元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。
- inherit
- 规定应该从父元素继承 position 属性的值。
垂直居中——1
.wrap-vertical {
height: 500px;
}
#vertical-center {
background: #ffdb4c;
width: 200px;
height: 200px;
margin: 0 auto;
position: relative;
top: 50%;
transform: translateY(-50%);
}
I'm a block, I want to vertical center
** 代码中的transform是css3的特性,表示向上平移当前元素高度的50%,也可以用于水平居中,类似于relative block的水平居中
垂直居中——2
/*表格布局法*/
.display-table {
display: table;
}
.display-table-cell {
display: table-cell;
vertical-align: middle;
}
.wrap-table-cell {
width: 100%;
height: 200px;
}
#table-cell {
background: #ffdb4c;
width: 100px;
height: 100px;
}
I'm a block display in a table-cell