前端一锅煮

css 布局:两边固定中间自适应

2018-10-16  本文已影响38人  1920de65b6bb

解析四种常用方法以及原理:浮动、浮动内嵌 div、定位、flex。

浮动

<style type="text/css">
    .wrap {background: #eee; padding: 20px; }
    p {margin: 0; }
    .left {width: 200px; height: 200px; float: left; background: coral; }
    .right {width: 200px; height: 200px; float: right; background: lightblue; }
    .middle {margin: 0 200px; background: lightpink; }
</style>

<div class="wrap">
    <p class="left">我在左边</p>
    <p class="right">我在右边</p>
    <p class="middle">我排最后,但是跑到中间来了</p>
</div>
image

原理:

浮动内嵌 div

<style type="text/css">
    .wrap {background: #eee; padding: 20px; }
    p {margin: 0; }
    .left {width: 200px; height: 200px; float: left; background: coral; margin-left: -100%;}
    .right {width: 200px; height: 200px; float: left; background: lightblue; margin-left: -200px;}
    .middle {width: 100%; height: 200px;float: left; background: lightpink; }
    span{
        display: inline-block;
        margin: 0 200px;
    }
</style>

<div class="wrap">
    <p class="middle">
        <span class="inner">
            我在中间
        </span> 
    </p>
    <p class="left">我在左边</p>
    <p class="right">我在右边</p>
</div>
image

原理:

定位

<style type="text/css">
    .wrap {background: #eee; position: relative;}
    p {margin: 0; }
    .left {width: 200px; height: 200px; background: coral; position: absolute;left: 0; top: 0;}
    .right {width: 200px; height: 200px; background: lightblue; position: absolute;right: 0; top: 0;}
    .middle {height: 200px; background: lightpink; margin: 0 200px;}
</style>

<div class="wrap">
    <p class="middle">我在中间,我用 margin 抵消左右两块定位元素占据空间</p>
    <p class="left">我在左边,我是定位元素</p>
    <p class="right">我在右边,我是定位元素</p>
</div>
image

原理:

flex

<style type="text/css">
    .wrap {background: #eee; display: flex}
    p {margin: 0; }
    .left {width: 200px; height: 200px; background: coral; }
    .right {width: 200px; height: 200px; background: lightblue; }
    .middle {height: 200px; background: lightpink; flex: 1;}
</style>

<div class="wrap">
    <p class="left">我在左边</p>
    <p class="middle">我在中间,flex: 1 自动占据剩余空间</p>
    <p class="right">我在右边</p>
</div>

原理:

上一篇 下一篇

猜你喜欢

热点阅读