頁面架構(筆記3)——水平垂直都居中佈局
阿新 • • 發佈:2020-12-11
需求要求:
1.子容器相對父容器水平居中、垂直居中
2,子容器與父容器的自身高度寬度都是未知的
解決方案一(inline-block+text-align+table-cell+vertical-align)
<style type="text/css"> body{margin:20px;} .parent{width:200px;height:300px;} .parent{ text-align: center; display: table-cell; vertical-align: middle; } .child{ display: inline-block; } </style>
<body> <div class="parent"> <div class="child">DEMO</div> </div> </body>
解決方案二(absolute+transform)
<style type="text/css"> body{margin:20px;} .parent{width:200px;height:300px;} .parent{ position: relative; } .child{ position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); } </style> <body> <div class="parent"> <div class="child">DEMO</div> </div> </body>
解決方案三(flex+justify-content+align-items)
<style type="text/css"> body{margin:20px;} .parent{width:200px;height:300px;} .parent{ display: flex; justify-content: center; align-items: center; } </style> <body> <div class="parent"> <div class="child">DEMO</div> </div> </body>
例子:
我們剛學習了定位中的固定定位,那麼我們就來實現無論頁面怎麼滾動,紅色的div塊都固定在頁面的最上面,並且水平居中顯示。
具體效果如下:
任務
1、想要固定的顯示在某個部位,肯定是要用到position:fixed。
2、固定在頁面的頂端,那麼就給top設定為0,不過預設情況下top的值是0,所以可以省略。
3、要在頁面中水平居中顯示,那麼我們就需要設定左邊為50%,但是設定完了之後會發現紅色的div塊並沒有居中,此時我們就需要將div塊再向左移動div塊一半的距離
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin: 0;
padding:0;
}
.test{
width: 800px;
height: 100px;
background: red;
/*此處寫程式碼*/
position:fixed;
top:0;
left:50%;
left: 50%;
/*top: 50%;*/
transform: translate(-50%,-50%);
}
.out{
width: 100%;
height: 2000px;
background-color: #abcdef;
}
</style>
</head>
<body>
<div class="out">
<div class="test"></div>
</div>
</body>
</html>
reference: