美文网首页
css固定宽高的元素撑满屏幕定位

css固定宽高的元素撑满屏幕定位

作者: 夏_至 | 来源:发表于2016-07-03 18:24 被阅读618次

    初学css的时候需要多个div并排排列的时候,通常会使用百分比定位,再用float去排列,例如a,b,c三个div,这样百分比定位的好处是自适应,只要定义好div的属性,保证每个div的内容不溢出,则可以一直保持效果
    <pre>
    #a{ width: 33%; float: left;}
    #b{ width: 33%; float: left;}
    #c{ width: 33%; float: left;}
    </pre>


    Paste_Image.png

    纵向排列也是类似的,设定好宽度,高度再去百分比就可以了
    <pre>
    #a{ height: 33%; width:100; float: left;}
    #b{ height: 33%; width:100; float: left;}
    #c{ height: 33%; width:100; float: left;}
    </pre>
    然而现实开发中真正需要这种简单的百分比定位的却不多,很多情况下都需要,某些列某列固定宽度,其他列自动适应,例如左侧a元素需要固定100px,右侧的c元素固定50px,中间b元素自适应,这里就需要使用到绝对定位了,position:absolute
    <pre>
    #a{
    position:absolute;
    left:0;
    top:0;
    width: 100px;
    }
    #b{
    position:absolute;
    left: 100px;
    right: 50px;
    top:0;
    width: auto;
    }
    #c{
    position:absolute;
    right:0;
    top: 0;
    width: 50px;
    }
    </pre>

    Paste_Image.png

    原理是:
    absolute定位是指针对父元素绝对定位,abc都为绝对定位,a元素距离左侧0px,宽度100px,等于完全靠左,c元素距离右侧0px,宽度50px,指定起点和宽度等于就已经固定了一个元素的绝对位置了,不管浏览器怎么拉伸怎么缩小,除非宽度小于100+50px,否则都不会变形。而b元素没有定义固定宽度,只定义了距离左侧的像素和距离右侧的像素,这样就实现了自动拉伸元素宽度。

    同理竖列定位也如此,例如我们想实现同时显示头尾,并且中间部分内容滚动效果:
    <pre>

    a{

    position:absolute;
    left:0;
    top:0;
    width: 100%;
    height: 100px;
    background-color: lightblue;
    }

    b{

    position:absolute;
    top:100px;
    left: 0;
    bottom: 150px;
    width: 100%;
    overflow-y: scroll;
    }

    c{

    position:absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 150px;
    background-color: lightblue;
    }
    </pre>

    Paste_Image.png
    有关定位是比较复杂的东西,一些绝对定位中夹杂着相对定位,而且各个浏览器的兼容性不尽相同,需要多调试才能出效果~
    推荐一篇定位的入门知识:
    http://www.cnblogs.com/morsh/archive/2009/11/26/1611456.html

    相关文章

      网友评论

          本文标题:css固定宽高的元素撑满屏幕定位

          本文链接:https://www.haomeiwen.com/subject/fuhcjttx.html