页面左右布局
例如:现有一个页面,需要左侧200px,右侧自适应页面宽度。
页面代码如下:
import React, { Component } from 'react';
import styles from './CssLayout.less';
export default class CssLayout extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className={styles.layoutBox}>
<div className={styles.leftLayout}>左侧菜单</div>
<div className={styles.rightLayout}>右侧内容</div>
</div>
)
}
}
下面提供几种布局方式:
1.calc计算右侧宽度
.layoutBox {
height: 100vh;
.leftLayout {
width: 200px;
background: #000;
float: left;
height:100%;
color:#fff;
}
.rightLayout {
width: calc(~"100% - 200px");
background: #fff;
float: left;
height:100%;
}
&:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
}
这种方式是calc计算和float结合的结果,需要注意的是必须清除浮动,避免浮动影响其他内容展示。另外less中的calc写法有点特殊,这是由于less的计算方式与calc相冲突导致的。
2.position定位加padding偏移
.layoutBox {
height: 100vh;
position: relative;
.leftLayout {
position: absolute;
width: 200px;
background: #000;
height: 100%;
color: #fff;
z-index: 10;
}
.rightLayout {
width: 100%;
background: #fff;
height: 100%;
padding-left: 200px;
}
}
该模式下需要设置
z-index: 10;
,防止右侧空出的页面遮挡左侧菜单。
3.flex布局
.layoutBox {
height: 100vh;
display: flex;
.leftLayout {
width: 200px;
background: #000;
height: 100%;
color: #fff;
flex-shrink: 0;
}
.rightLayout {
width: 100%;
background: #fff;
height: 100%;
flex: 1;
}
}
这里左侧菜单设置
flex-shrink: 0;
是为了防止父元素缩放影响到子元素。
4.float浮动加padding偏移
/*float+padding*/
.layoutBox {
height: 100vh;
.leftLayout {
width: 200px;
background: #000;
height: 100%;
color: #fff;
float: left;
}
.rightLayout {
width: 100%;
background: #fff;
height: 100%;
padding-left: 200px;
}
&:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
}
这里右侧布局设置
padding-left: 200px;
是为了防止左侧脱离了正常文档流的菜单影响内容显示。这种方式是利用了html文档流布局的方式,float会使元素脱离文档流,悬浮于正常文档流之上。
效果图:
当然了,这里只是一个简单的定式布局例子,只是为了让大家了解一下常用的布局思路,不要被局限了,实际上还有其他的布局方式,这里就不一一列举了。实际应用中更多用到的是响应式布局,大家利用这些思维模式就能很快的找到适合自己的布局方式了。