响应50%2列html / css

时间:2014-01-03 10:44:11

标签: html css html5 css3

我怀疑使用纯HTML / CSS可能无法实现我想要实现的目标,但无论如何都要进行。我想要一个2列布局,它很好地包装在移动设备上。如果有空间,每列占据容器宽度的50%,如果它们包裹,则占据容器宽度的100%。

以下是一些示例标记:

<!doctype html>
<html xml:lang="en-gb" lang="en-gb" >
<head>
    <title>Responsive 2 col</title>
    <style type="text/css">
        .colcontainer
        {
            width: auto;
            overflow:hidden;
            border: solid 1px red;
        }
        .leftcol
        {
            width: 49%;
            float: left;
            margin-right:10px;
            border: solid 1px blue;
        }
        .rightcol
        {
            width: 49%;
            float: left;
            border: solid 1px green;
        }
    </style>
</head>
<body>
    <div class="colcontainer">
        <div class="leftcol">
            Here is a paragraph which has enough text to cause it to take up a fair amount of width if left to its own devices.
        </div>
        <div class="rightcol">
            A smaller paragraph.
        </div>
    </div>
</body>

这看起来不错但是当你压缩浏览器宽度以使div换行时,它们仍然只占用容器宽度的50%。通过移除宽度:49%,它可以很好地包裹并填充可用的宽度,但是在未包裹时不再均匀地分割列。是否有任何方法可以让它们在包裹时填充可用的宽度,但在没有包裹时占用可用宽度的50%?

1 个答案:

答案 0 :(得分:5)

这里你需要多个东西,首先你要制作一个响应式网格,所以每当你做出回应的事情时,一定要使用下面的CSS片段

* {
   margin: 0;
   padding: 0;
   -moz-box-sizing: border-box;
   -webkit-box-sizing: border-box;
   box-sizing: border-box;
}

这会更改框模型的行为,并会计算框内的paddingborder而非外部..

其次,如果要包装元素,可以使用@media查询声明断点,这样它们就不会被压扁。

Demo (调整窗口大小并查看效果)