且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

两列布局,固定右列

更新时间:2023-10-25 17:18:34

不是一个非常优雅的解决方案,但它的工作。它们的关键是包装左列的内容,并添加一个margin-right等于右列/侧边栏的宽度。在右侧栏中,设置宽度,并将左侧的负边距设置为其宽度。

  .left {
float:left;
width:100%;
background-color:green;
}
.left-content {
margin-right:120px;
}
.right {
float:right;
width:120px;
margin-left:-120px;
background-color:red;
}

这里是一个工作的小提琴
http://jsfiddle.net/heyapo/9Z363/


I am stuck with a seemly simple two column CSS layout. Typically this layout is simple but I am building a responsive site and need the columns to collapse in the correct order for mobile, on top of each other.

On desktop, I need the right column to be fixed size, say 200px and the rest of the area to be taken up by the left column. Naturally I need the columns to clear and push content below down.

On mobile, they would just stack. So the left column is above the right column.

As mentioned before, this type of layout is usually accomplished simply by floating one of the columns and/or setting large margins, but this approach requires the left and right to be swapped in the document flow and would make the collapsed mobile version impossible.

I have even looked at display table and table-cell, this works relatively well for the most part, but unfortunately FireFox does not support absolute positioned elements within the layout breaking some of the content within.

I'm a seasoned developer, surly accomplishing this should be simpler that I am finding?

Not a very elegant solution, but its working. They key is to wrap the contents of the left column and add a margin-right equal to the width of the right column / sidebar. On the right column, set the width and a negative margin-left equal to its width.

.left {
    float:left;
    width:100%;
    background-color: green;
}
.left-content {
    margin-right:120px;
}
.right {
    float:right;
    width: 120px;
    margin-left: -120px;
    background-color: red;
}

Here's a working fiddle http://jsfiddle.net/heyapo/9Z363/