右边宽度固定,左边自适应的三种方法

版权声明:哼!坏人!这是我辛辛苦苦码的! https://blog.csdn.net/DurianPudding/article/details/87879974
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>右边宽度固定,左边自适应</title>
  <style>
    html, body {
      margin: 0;
    }
    div {
      height: 100px;
    }

    .div1 .left {
      background-color: blue;
      margin-right: 100px;
    }
    .div1 .right {
      float: right;
      width: 100px;
      background-color: red;
    }

    .div2 .left {
      background-color: blue;
      margin-right: 100px;
    }

    .div2 .right {
      position: fixed;
      right: 0;
      width: 100px;
      background-color: red;
    }

    .div3 {
      display: flex;
    }
    .div3 .left {
      flex: 1;
      background-color: blue;
    }

    .div3 .right {
      width: 100px;
      background-color: red;
    }
  </style>
</head>
<body>
<h1>右边宽度固定,左边自适应</h1>
<h2>方法一:利用flex布局</h2>
<pre>参考:<a href="http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html?utm_source=tuicool" target="_blank">flex布局</a>
     <a href="http://static.vgee.cn/static/index.html" target="_blank">flex属性</a>
</pre>
<div class="div3">
  <div class="left"></div>
  <div class="right"></div>
</div>
<p>注意:要先将父div的display属性设置成flex,则左右块成为该容器中项目。默认主轴正向排列,设置左块可拉伸,右块固定宽度。</p>

<h2>方法二:<strong>右方块利用浮动float,不占空间。</strong>左方块用margin</h2>
<div class="div1">
  <div class="right"></div>
  <div class="left"></div>
</div>
<p>注意:要先写right再写left,因为left占据一行空间,right才浮动不占空间。否则right就会挤到left下一行的右侧,如下图:</p>
<div class="div1">
  <div class="left"></div>
  <div class="right"></div>
</div>

<h2 style="margin-top: 100px;">方法三:右方块利用绝对定位absolute,不占空间,固定在右侧。左同上</h2>
<div class="div2">
  <div class="right"></div>
  <div class="left"></div>
</div>
<p>注意:如果用fixed代替absolute。因为fixed相对于浏览器窗口固定,所以只有当父元素与浏览器窗口同宽,结果成立。否则右侧与左侧中间有空白。</p>

</body>
</html>

猜你喜欢

转载自blog.csdn.net/DurianPudding/article/details/87879974