简体   繁体   中英

CSS: 2 columns layout without <table> and with first column variable height

I would like:

  1. To design a 2-column layout: 1 fixed width (say 200px) and the other one using all the remaining width room
  2. The first one height is variable and unknown, and I don't want it outside its parent flow

Before using CSS, I would have simply used a <table> with two <td> to do that. With CSS, and for now, I use an approach based on float left column + left-padded right column + clear both <div> after:

.container2 .columnLeft {
  float: left;
  width: 200px;
}

.container2 .columnRight {
  padding-left: 200px;
}

But I am not sure this is a correct approach. Could you tell me how you would do it please ?

Please use and modify http://jsfiddle.net/rjjr24sf/4/ at your convenience.

Thanks,

Using flexbox:

.container {
    display: flex;
}
.container .columnLeft {
    width: 200px;
}
.container .columnRight {
    flex: 1; /* Grow to rest of width */
}

You can use the display CSS property to make your divs behave like table cells. This is done by setting display: table; on the parent, and display: table-cell; on the children.

Try this code:

.container {
   display: table;
}

.container .columnLeft {
    width: 200px;
    display: table-cell;
}

.container .columnRight {
    display: table-cell;
}

The only difference using this method is that your first fixed column will take up the same height as it's parent, the same as a td would. Although, you can fix this by adding float: left; onto your children.

Updated Fiddle

http://jsfiddle.net/bgBXM/10/

#RightColumn {
margin-left: 200px;
background-color: blue;
}

#LeftColumn {
float : left;
width: 200px;
background-color: red
}

<div id="Container">
<div id="LeftColumn">Left column</div>
<div id="RightColumn">Right column</div>
</div>

You can also use CSS calc method to achieve that, as per this fiddle - http://jsfiddle.net/aewqgh7t/
so markup:

<div class="container2">
    <div class="columnLeft">
        Some Content<br/>
        Some Content<br/>
        Some Content<br/>
        Some Content<br/>
        Some Content
    </div>
    <div class="columnRight">
        Some Content
    </div>
</div>   

css:

.container2 { 
   width:100%; 
   background: lightgrey; 
   overflow:hidden; 
}
.columnLeft { 
   background: salmon; 
   float:left; 
   width:200px; 
}
.columnRight { 
   background: darkblue; 
   float:left; 
   margin-left:20px; 
   width: calc(100% - 220px) /* To calculate remaining space */; 
}   

You also need to consider browser support for calc css function: CanIUse

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM