1

I'm making a responsive list with floated <li>'s, where I want the list to stay with three columns. However, when resizing the window the floated items are pushed – as with fixed items – into two columns, instead of resizing. Here's an example of my code:

#list {
  position: relative;
  width: 100%;
  display: block;
}

#list li {
  position: relative;
  width: 27%;
  float: left;
  margin: 2% 2% 0 0;
  display: block;
}
<ul id="list">
  <li>item1</li>
  <li>item1</li>
  <li>item1</li>
  <li>item1</li>
  <li>item1</li>
  <li>item1</li>
<ul>

4

1 回答 1

4

N 列布局中 % 和 maring/padding 的问题是像素舍入

如果您定义 2%+2%+2% 填充,没有四舍五入它可能是20.4px+20.4px+20.4px=61.2px. 但随着四舍五入它会给20px+20px+20px=60px

此外,不同的浏览器可能会以不同的方式舍入像素。假设 2% 等于 20.7px。一些浏览器可能会将其四舍五入为 20 像素,其他浏览器可能会舍入为 21 像素。


如果需要结合 % 和一些边距/填充,可以使用内部元素。到目前为止,我发现的跨浏览器解决方案是最好的:

HTML:

   <ul id="list">
       <li><span>item1</span></li>
       <li><span>item1</span></li>
       <li><span>item1</span></li>
       <li><span>item1</span></li>
    <ul>

CSS:

#list{
    position: relative;
    width: 100%;
    display: block;
}

#list li {
    width: 33.3%; /* nice 3 columns */
    float: left;
    padding: 0; /* should have zero paddng/margin */
    margin: 0;
}

#list li > span {
 margin: 6% 6% 0 0; /* now margins are specified relative to outer <li> width */
 display: block;
}

此外,您可以为较小的屏幕尺寸指定两列:

@media only screen and (max-width: 800px) {
   #list li {
        width: 49.9%;
   }
}
于 2013-10-11T07:41:37.970 回答