ch8 高度相等的列--CSS方法

如下图所示效果,可以使用表格实现,本文采用在CSS中实现。

标记如下:

<div class="wrapper">
    <div class="box">
        <h1>Andy Budd</h1>
        <p> ... </p>
        <div class="bottom"></div>
    </div>
    <div class="box">
        <h1>Richard Rutter</h1>
        <p> ... </p>
        <div class="bottom"></div>
    </div>
    <div class="box">
        <h1>Jeremy Keith</h1>
        <p> ... </p>
        <div class="bottom"></div>
    </div>
</div>

在实例中,有3个div,每列一个div,每个div中包括标题、内容、空的div,这个空的div作为底角的钩子,将这3个div放入容器div中,使用容器div限制高度,下述代码给框设置样式:

.wrapper {
    width: 100%;
}
.box {
    width: 250px;
    margin-left: 20px;
    float: left;
    display: inline;
    padding: 20px;
    background: #89ac10 url(chapter08/img/top.gif) no-repeat left top;  /*图片使得上面两个角成为圆角*/
}

运行结果如下:产生3个高度不一致的列

产生高度相等的三列的关键技术在于:给每个框设置大的底内边距(220px),然后用数值相似的负外边距(-200px)来消除这个高度。

.wrapper {
    float: left;
    border: solid 1px black;
    width: 100%;
}
.box {
    width: 250px;
    padding-left: 20px;
    padding-right: 20px;
    padding-top: 20px;
    padding-bottom: 220px;
    margin-bottom: -200px;
    margin-left: 20px;
    float: left;
    display: inline;
    background: #89ac10 url(chapter08/img/top.gif) no-repeat left top;
}

通过给容器浮动、添加边框,可以看到这样导致每个列溢出容器元素。

.wrapper {
    border: solid 1px black;
    width: 100%;
    overflow:hiddden;
}
.box {
    width: 250px;
    padding-left: 20px;
    padding-right: 20px;
    padding-top: 20px;
    padding-bottom: 220px;
    margin-bottom: -200px;
    margin-left: 20px;
    float: left;
    display: inline;
    background: #89ac10 url(chapter08/img/top.gif) no-repeat left top;
}

如果把容器的overflow设置为hidden,列在最高点被剪裁,220px和-200px形成的20px的差值在每个框的底部形成可见的内边距。

下面把列的底边定位在正确的位置,需要它们与容器的底部对齐:为此,把容器的position设置为relative,然后将空div的position设置为absolute,再将它们的bottom设置为0,只要给它们设置正确的宽高,就能应用底部背景图像。

.wrapper {
    border: solid 1px black;
    width: 100%;
    overflow:hiddden;
    position: relative;
}
.box {
    width: 250px;
    padding-left: 20px;
    padding-right: 20px;
    padding-top: 20px;
    padding-bottom: 220px;
    margin-bottom: -200px;
    margin-left: 20px;
    float: left;
    display: inline;
    background: #89ac10 url(chapter08/img/top.gif) no-repeat left top;
}
.bottom {
    position: absolute;
    bottom: 0;
    height: 20px;
    width: 290px;
    background: #89ac10 url(chapter08/img/bottom.gif) no-repeat left bottom;
    margin-left: -20px;/*因为在.box中设置了margin-left为20px,则.bottom向右移动了20px(如最后一图),所以设置-20px让它左移*/
}
posted @ 2017-10-26 19:12  L_mj  阅读(304)  评论(0编辑  收藏  举报