居中的分類
一,塊級元素內的內聯元素水平居中,text-align: center;
- div.box里面有文字,讓文字在盒子內居中
<style type="text/css">
.box {
border: 1px solid red;
text-align: center;
}
</style>
<div class="box">
hello deejay
</div>
- 盒子內部是按鈕的情況
<style type="text/css">
.box {
border: 1px solid red;
text-align: center;
}
</style>
<div class="box">
<a href="#">click me!</a>
<a href="#">click me!</a>
</div>
二,固定寬度的塊級元素水平居中,margin:0 auto
<style type="text/css">
.box {
border: 1px solid red;
text-align: center; /*讓a鏈接也居中*/
}
.box2 {
width: 500px;
border: 1px solid green;
margin: 0 auto; /*固定寬度的塊級元素居中*/
}
</style>
<div class="box">
<div class="box2">
<a href="#">Click me!</a>
</div>
</div>
三,盒子內部的文字垂直居中
可以設置padding,使得上下padding相等,就做到了垂直居中
<style type="text/css">
.box{
border: 1px solid red;
padding: 30px 0; /*不設置高度,box里面的內容不管有多少行都是垂直居中的,只要設置上下padding相等。*/
}
</style>
<div class="box">
<p>hello deejay ello deejay</p>
<p>hello deejay ello deejay</p>
<p>hello deejay ello deejay</p>
</div>
- 針對單行文本的垂直居中
可以通過設置height=line-height來實現單行文本的居中
四,絕對水平垂直居中
對于沒有固定的寬高的父元素要進行子元素的垂直水平居中,可以采用絕對定位,left: 50%,結合負的margin-left來進行定位。
<style type="text/css">
*{
margin: 0; /*初始化樣式,不然body會有默認margin等*/
padding: 0;
}
body,html{ /*box要寬高都設置100%全屏的話,要將其父元素都設置成寬高100%,本例中就是body和html*/
width: 100%;
height: 100%;
}
.box{
width: 100%;
height: 100%;
background: rgba(0,0,0,0.4);
position: relative;
}
.box2{
width: 500px;;
height: 400px;
background: green;
position: absolute;
left: 50%;
margin-left: -250px; /*自身width的一半*/
top: 50%;
margin-top: -200px; /*同理,自身height的一半*/
}
</style>
<div class="box">
<div class="box2">
<h1>hello,deejay</h1>
</div>
</div>
- 上述例子中,子元素的寬高并沒有固定的情況:
可以使用CSS3的屬性transform: translate(-50%,-50%);來進行居中
<style type="text/css">
*{
margin: 0; /*初始化樣式,不然body會有默認margin等*/
padding: 0;
}
body,html{ /*box要寬高都設置100%全屏的話,要將其父元素都設置成寬高100%,本例中就是body和html*/
width: 100%;
height: 100%;
}
.box{
width: 100%;
height: 100%;
background: rgba(0,0,0,0.4);
position: relative;
}
.box2{
/*width: 500px;*/
/*height: 400px;*/
background: green;
position: absolute;
transform: translate(-50%,-50%);
left: 50%;
/*margin-left: -250px; !*自身width的一半*!*/
top: 50%;
/*margin-top: -200px; !*同理,自身height的一半*!*/
}
</style>
<div class="box">
<div class="box2">
<h1>hello,deejay</h1>
</div>
</div>