2012-11-23 72 views
0

好的,所以我错过了一些东西,但我似乎无法列出一个简单的ul列表项目列表,以便它们伸展其父div的整个宽度。这里是我的问题http://jsfiddle.net/37E55/17/的一个例子。水平排列列表项目

我想要做的是让灰盒子排成一行,以便第一个盒子的左手边缘与#wrapper div的左手边缘内嵌,并且最后一个盒子的右手边缘与内联#wrapper div的右手边。

我已经试过成功地通过给他们一个绝对定位,但有没有办法使用余量和填充,我失踪的组合?

#wrapper { 
width: 400px; 
height: 300px; 
background-color:#F0F0F0; 
margin: 10px auto;  
} 

.box { 
width: 92px; 
height:92px; 
background-color:#333; 
margin:0px 10px 10px 0px; 
float:left; 
} 

<div id="wrapper"> 

<ul> 
    <li class="box"></li> 
    <li class="box"></li> 
    <li class="box"></li> 
    <li class="box"></li> 
</ul> 

</div>​ 

回答

2

我知道有一种方法可以用inline-block而不是浮动(如果您不必支持过时的浏览器)。

Here's a fiddle demo

li没有使用保证金,它们均匀地设置在区域附着于边界。我跟着this guide

ul { 
    font-size: 0 !important; /* remove physical spaces between items */ 
    text-align: justify; 
    text-justify: distribute-all-lines; /* distribute items in IE */ 
    list-style-type: none; 
    margin: 0; 
    padding: 0; 
} 

/* fully justify all items in browsers other than IE */ 
ul:after { 
    content: ""; 
    display: inline-block; 
    width: 100%; 
} 

ul li { 
    text-align: left; /* customize to suit */ 
    vertical-align: top; /* can customize to suit */ 
    display: inline-block; 
    width: 31.3%; /* optional, only need for text content to wrap */ 
    margin-bottom: 1em; /* optional, customize to suit */ 
} 
+0

嗨@Kraz很好的解决方案,我认为这将是一件非常容易的事情! – user1563944

1

您需要做的第一件事是删除最后一个元素的右边距。

.box:last-child { margin-right:0; } 

除此之外,有时你不必以适合元素的能力,例如,确切的利润率甚至根据自己的空间和容器的大小。有时你可以(例如)每隔一个元素上应用不同的利润率将保持布局看“偶”,但处理空间不足,是这样的:

.box:nth-of-type(2n) { margin-right:14px } /* add extra pixels to right margin of even elements*/ 

在你的情况虽然,只有一个盒子需要额外的利润,比如说第一个。 Here's how I did it(增加颜色对比度使其更容易看清)。

.box { 
    width: 90px; 
    height:90px; 
    background-color:blue; 
    margin:0px 13px 10px 0px; 
    float:left; 
} 

.box:last-child { 
    background:green; 
    margin-right:0; 
} 

.box:first-child { 
    background:yellow; 
    margin-right:14px; 
} 

干杯

+0

不要使用'first-child'和'last-child'选择器。 IE仍然存在。 – GiantDuck

+0

Hi @Madbreaks感谢您的评论。我有种感觉,有可能只用边距和填充来排队,但去掉最后一个小孩的边距效果很好 – user1563944

+0

很好听。除了接受正确的答案之外,您可能会“考虑对您认为有帮助的任何答案进行投票。这将鼓励人们在未来帮助你。除非你不觉得其他贡献是有帮助的。:) – Madbreaks

0

您与利润率箱子太大。请注意,填充是指定的heightwidth的补充。看到它的工作http://jsfiddle.net/37E55/32

+0

你的例子不符合op的要求 – Madbreaks

+0

我改变了它:http://jsfiddle.net/37E55/32/ – GiantDuck

+0

我不能撤消我downvote,除非你编辑你的答案 – Madbreaks

1

使用:last-child选择最后一个框,并应用margin-right: 0它。确保剩余边距将正确填充空间。

.box { 
    width: 92px; 
    height:92px; 
    background-color:#333; 
    margin:0px 10px 10px 0px; 
    float:left; 
} 

.box:last-child { 
    margin-right: 0; 
} 

如果你必须坚持92px的宽度,你不会让他们正确对齐。余下需要填充的空间是32px,它不会均匀分配3.