Setting a div's height in HTML with CSS

前端 未结 14 956
无人共我
无人共我 2020-12-05 09:36

I am trying to lay out a table-like page with two columns. I want the rightmost column to dock to the right of the page, and this column should have a distinct background c

14条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 09:53

    Some browsers support CSS tables, so you could create this kind of layout using the various CSS display: table-* values. There's more information on CSS tables in this article (and the book of the same name) by Rachel Andrew: Everything You Know About CSS is Wrong

    If you need a consistent layout in older browsers that don't support CSS tables, you need to do two things:

    1. Make your "table row" element clear its internal floated elements.

      The simplest way of doing this is to set overflow: hidden which takes care of most browsers, and zoom: 1 to trigger the hasLayout property in older versions of IE.

      There are many other ways of clearing floats, if this approach causes undesirable side effects you should check the question which method of 'clearfix' is best and the article on having layout for other methods.

    2. Balance the height of the two "table cell" elements.

      There are two ways you could approach this. Either you can create the appearance of equal heights by setting a background image on the "table row" element (the faux columns technique) or you can make the heights of the columns match by giving each a large padding and equally large negative margin.

      Faux columns is the simpler approach and works very well when the width of one or both columns is fixed. The other technique copes better with variable width columns (based on percentage or em units) but can cause problems in some browsers if you link directly to content within your columns (e.g. if a column contained

      and you linked to #foo)

    Here's an example using the padding/margin technique to balance the height of the columns.

    html, body {
      height: 100%;
    }
    
    .row {
      zoom: 1;          /* Clear internal floats in IE */
      overflow: hidden; /* Clear internal floats */
    }
    
    .right-column,
    .left-column {
      padding-bottom: 1000em;  /* Balance the heights of the columns */
      margin-bottom: -1000em;  /*                                    */
    }
    
    .right-column {
      width: 20%;
      float: right;
    }
    
    .left-column {
      width: 79%;
      float: left;
    }
    Right column content
    Left column content
    Right column content
    Left column content

    This Barcamp demo by Natalie Downe may also be useful when figuring out how to add additional columns and nice spacing and padding: Equal Height Columns and other tricks (it's also where I first learnt about the margin/padding trick to balance column heights)

提交回复
热议问题