页面左右布局

页面左右布局

例如:现有一个页面,需要左侧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会使元素脱离文档流,悬浮于正常文档流之上。

效果图:
在这里插入图片描述

当然了,这里只是一个简单的定式布局例子,只是为了让大家了解一下常用的布局思路,不要被局限了,实际上还有其他的布局方式,这里就不一一列举了。实际应用中更多用到的是响应式布局,大家利用这些思维模式就能很快的找到适合自己的布局方式了。

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值