1. 程式人生 > >運用flex和rem為移動端佈局

運用flex和rem為移動端佈局

flex是對於頁面一個非常重要的樣式,不會用到px來佈局,用rem來代替 rem是根據根文件,也就是html標籤上的字型大小來運算的1rem=16px; 手機端的佈局也很簡單,掌握好flex所有的屬性和rem寫頁面就是一件很輕鬆的事。 flex的知識過多,咱們只說能應用到的:

HTML

<!DOCTYPE html>
<html lang="zh">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0"
/>
<meta http-equiv="X-UA-Compatible" content="ie=edge" /> <link rel="stylesheet" type="text/css" href="new_file.css" /> <title>flexPhone</title> </head> <body> <div class="container"> <div class="nav"> <div class="nav-header">Logo</
div
>
<!--商標--> <ul class="nav-right"> <li>Demo 1</li> <li>Demo 2</li> <li>Demo 3</li> <li>Demo 4</li> </ul> </div> <!--導航--> <div class="Pagebody"> <div class="banner">
</div> <!--banner圖--> <div class="main"> </div> <!--主體內容--> </div> <!--主體部分--> <div class="footer"> <div class="footer-list">List 1</div> <div class="footer-list">List 2</div> <div class="footer-list">List 3</div> <div class="footer-list">List 4</div> </div> <!--底部選框--> </div> </body> </html>

CSS

* {
	margin: 0;
	padding: 0;
	list-style: none;
}

html,
body,
.container {
	width: 100%;
	height: 100%;
	font-size: 100px;
}

.container {
	font-size: 0.12rem !important;
	display: flex;
	flex-direction: column;
}

.nav {
	top: 0;
	border-bottom: 0.01rem solid lightgray;
}

.nav,
.footer {
	background: linear-gradient(to bottom, #333, #444, #333);
	color: white;
	position: fixed;
	width: 100%;
	height: 0.5rem;
	box-sizing: border-box;
	padding: .16rem 0.16rem;
}

.footer {
	border-top: 0.01rem solid lightgray;
	bottom: 0;
	display: flex;
	align-items: center;
	justify-content: space-around;
}

.nav .nav-header {
	font-weight: bold;
	color: #fff;
	line-height: 100%;
	font-size: 0.18rem;
	float: left;
}

.nav .nav-right {
	float: right;
}

.nav .nav-right li {
	float: left;
	margin-left: 0.12rem;
}

.Pagebody {
	flex:1;
	padding-top: 0.5rem;
}

.banner {
	width: 100%;
	height: 1.5rem;
	background: cornflowerblue;
}

.main{
	box-sizing: border-box;
	height: auto;
	padding:0 0.16rem;
}

效果演示

在這裡插入圖片描述

書寫時注意↓

  1. meta標籤
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />

這是在移動端佈局時必須有的標籤,意思是能讓使用者縮放螢幕的大小,頁面寬度=裝置寬度,我在這裡用的裝置型號是iPhone5的螢幕

  1. html和body及自定義一個盒子來包裹頁面,即 .container 這裡把html的字型設為100px,那麼rem就與px成了百倍的關係;即,1rem=100px

  2. 涉及到的flex

display: flex;	/*顯示方式設定為flex*/
flex-direction: column;  /*顯示方向為 縱向*/
flex:1;			/*分配為1份,加入有兩個pagebody每個就佔總高的1/2*/
align-items: center;	/*設定軸線上子元素 為 居中*/
justify-content: space-around;	/*排列方式 為 平均分配 且 兩端留有空餘*/