首頁 > web前端 > css教學 > 主體

css如何設定垂直居中

青灯夜游
發布: 2023-01-05 16:10:27
原創
58213 人瀏覽過

css設定垂直居中的方法:1.使用line-height屬性讓文字垂直居中;2、使用CSS3 flex佈局讓文字垂直居中;3、使用絕對定位和transform讓塊狀元素垂直居中; 4.使用flex佈局讓塊狀元素垂直居中。

css如何設定垂直居中

本教學操作環境:windows7系統、CSS3&&HTML5版、Dell G3電腦。

css設定文字文字垂直居中

#1、line-height 讓文字垂直置中

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>css 垂直居中</title>
<style>
.box{
    width: 300px;
    height: 300px;
    background: paleturquoise;
    line-height:300px;
}
</style>
</head>
<body>
<div class="box">css 垂直居中了--文本文字</div>
</body>
</html>
登入後複製

效果圖:

css如何設定垂直居中

這樣就能讓div中的文字水平垂直居中了

2、CSS3的flex佈局使文字垂直居中

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>css 垂直居中</title>
<style>
.box{
   width: 300px;
   height: 200px;
   background: paleturquoise;
   /*设置为伸缩容器*/
   display: -webkit-box;
   display: -moz-box;
   display: -ms-flexbox;
   display: -webkit-flex;
   display: flex;
   /*垂直居中*/
   -webkit-box-align: center;/*旧版本*/
   -moz-box-align: center;/*旧版本*/
   -ms-flex-align: center;/*混合版本*/
   -webkit-align-items: center;/*新版本*/
   align-items: center;/*新版本*/
}
</style>
</head>
<body>
<div class="box">css 垂直居中--文本文字(弹性布局)</div>
</body>
</html>
登入後複製

效果圖:

css如何設定垂直居中

#css設定塊狀元素垂直居中

1、使用絕對定位和transform(未知元素高度)

如果我們不知道元素的高度,那麼就需要先將元素定位到容器的中心位置,然後使用transform 的translate 屬性,將元素的中心和父容器的中心重合,從而實現垂直居中:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>css 垂直居中</title>
<style>
.box{
width: 300px;
    height: 300px;
    background: #ddd;
    position: relative;
}
.child{
background: #93BC49;
    position: absolute;
    top: 50%;
    transform: translate(0, -50%);
}
</style>
</head>
<body>
<div class="box">
    <div class="child">css 垂直居中,css 垂直居中,css 垂直居中,css 垂直居中,css 垂直居中</div>
</div>
</body>
</html>
登入後複製

效果圖:

css如何設定垂直居中

2、使用flex佈局

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>css 垂直居中</title>
<style>
.box{
width: 300px;
    height: 300px;
    background: #ddd;
    display: flex;
    flex-direction: column;
    justify-content: center;
}
.child{
width: 300px;
    height: 100px;
    background: #08BC67;
    line-height: 100px;
}
</style>
</head>
<body>
<div class="box">
    <div class="child">css 垂直居中了--弹性布局</div>
</div>
</body>
</html>
登入後複製

效果圖:

css如何設定垂直居中

(學習影片分享:css影片教學

以上是css如何設定垂直居中的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!