css中如何实现上下居中效果
這篇文章將為大家詳細講解有關css中如何實現上下居中效果,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
單行的行內元素
只需要設置單行行內元素的"行高等于盒子的高"即可;
<style>
#father{
width:500px;
height:300px;
background-color:skyblue;
}
#son{
background-color:green;
height:300px;
}
</style>
<divid="father">
<spanid="son">我是單行的行內元素</span>
</div>
效果:
1556519521438598.jpg
多行的行內元素
使用給父元素設置display:table-cell;和vertical-align:middle;即可;
<style>
#father{
width:500px;
height:300px;
background-color:skyblue;
display:table-cell;
vertical-align:middle;
}
#son{
background-color:green;
}
</style>
<divid="father">
<spanid="son">我是多行的行內元素我是多行的行內元素我是多行的行內元素我是多行的行內元素我是多行的行內元素我是多行的行內元素我是多行的行內元素我是多行的行內元素</span>
</div>
效果:
1556519558892168.jpg
塊級元素
方案一:使用定位
首先設置父元素為相對定位,再設置子元素為絕對定位,設置子元素的top:50%,即讓子元素的左上角垂直居中;
定高度:設置絕對子元素的margin-top:-元素高度的一半px;或者設置transform:translateY(-50%);
<style>
#father{
width:500px;
height:300px;
background-color:skyblue;
position:relative;
}
#son{
height:100px;
background-color:green;
position:absolute;
top:50%;
margin-top:-50px;
}
</style>
<divid="father">
<divid="son">我是塊級元素</div>
</div>
不定高度:利用css3新增屬性transform:translateY(-50%);
<style>
#father{
width:500px;
height:300px;
background-color:skyblue;
position:relative;
}
#son{
width:100px;
background-color:green;
position:absolute;
left:50%;
transform:translateY(-50%);
}
</style>
<divid="father">
<divid="son">我是塊級元素</div>
</div>
效果:
1556519576485117.jpg
方案二:使用flexbox布局實現(高度定不定都可以)
使用flexbox布局,只需要給待處理的塊狀元素的父元素添加屬性display:flex;align-items:center;
<style>
#father{
width:500px;
height:300px;
background-color:skyblue;
display:flex;
align-items:center;
}
#son{
width:100px;
height:100px;
background-color:green;
}
</style>
<divid="father">
<divid="son">我是塊級元素</div>
</div>
總結
以上是生活随笔為你收集整理的css中如何实现上下居中效果的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用JDK自带的VisualVM进行Ja
- 下一篇: JavaScript的语音识别