简体   繁体   中英

What is the best way to achieve a multi-column layout in CSS and HTML?

I have a problem in HTML. I have divided the HTML page into two columns:

My code:

<div id="outer">      
  <div id="inner1">
    <div id="data1">
    </div>
    <div id="response">
    </div>
  </div>

  <div id="inner2">
    <div id="data2">
    </div>
  </div>
</div>

My CSS:

#outer {
     background-color:#FFFF99;           
}
#inner1 {
     float: left;
     width: 62%;
}
#inner2 {
     float: right; 
     width: 38%;
}   

I need to insert another column #inner1_2 in between inner1 and inner2 which is the optional one.

There is also a third column:

<div id="#inner1_2">
</div>

The problem here is the variable division. Either I have three columns or two columns depending on the data:

  • inner2 is fixed
  • If there are three columns of data, .inner1 needs to be split into two halves, otherwise .inner1 remains as it is.

This is more complex logic than I am comfortable with in CSS.

What is the best way to handle this?

Add a class to the outer div that controls how the inner divs are displayed. Setting the class to "twoColumn" hides the middle column and setting the class to "threeColumn" shows the middle column:

<div id="outer" class="twoColumn">
   <div id="inner1">
      <div id="data1">
      </div>
      <div id="response">
      </div>
   </div>
   <div id="inner1_2">
   </div>
   <div id="inner2">
      <div id="data2">
      </div>
   </div>
</div>

css:

#outer { background-color: #FF9; }
#inner1 { float: left; }
#inner1_2 { float: left; }
#inner2 { float: left; width: 38%; }
.twoColumn #inner1 { width: 62% }
.twoColumn #inner1_2 { display: none; }
.threeColumn #inner1 { width: 31%; }
.threeColumn #inner1_2 { width: 31%; }

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