2012-12-15 97 views
1

我有一个div,每行有3个图像。图像的大小都一样。我一直在使用小而完全透明的透明图像,然后我会明确给出高度和宽度以在图像之间形成空间。举例如下:在HTML/CSS文档中创建空间的最佳方式是什么?

div begin 
space image width=15, height=1 actual image (no explicit dimensions) 
space image width=10, height=1 actual image (no explicit dimensions) 
space image width=10, height=1 actual image (no explicit dimensions) 

space image width=900, height=20 (this is to separate rows, which should be 900 wide, space + 3 x image) 

space image width=15, height=1 actual image (no explicit dimensions) 
space image width=10, height=1 actual image (no explicit dimensions) 
space image width=10, height=1 actual image (no explicit dimensions) 
div end 

这些行可能会或可能不会通过代码生成,并且有时会有hrefs。我意识到我可以使用图像/锚点元素上的边距/填充来创建空间。但是这需要在每个图像上设置一个类。这似乎不是一个好方法去做这件事。原因如下:空间位于锚标签内部,因此可以链接。我不会反对使用div和使用特定的类。然而,我已经尝试过了,而且他们似乎并没有像我期望的那样工作。他们创建换行符,所以现在图像出现在一列中,而且它们似乎也无法占用任何实际空间。

+2

这些问题在您的代码的参考中很难理解。请分享您制作的实际HTML代码,然后发布您的期望。 – Amber

回答

1

使用间隔图像相当笨拙并且几乎不需要。最简单的方法可能是将所有图像包含在a元素中,对于那些不意图成为链接的元素,仅使用<a><img ...></a>。然后,您可以在a元素上设置保证金,而不会使边距可点击。

您还可以将图像库以三行图像的格式进行格式化,而无需将这些分割部分作为HTML代码。例如:

.gallery img { border: 0; margin-bottom: 20px; } 
.gallery a:nth-child(3n+1) { margin-left: 15px; } 
.gallery a:nth-child(3n+2) { margin-left: 10px; margin-right: 10px; } 
.gallery a:nth-child(3n+3):after { content: "\A"; white-space: pre; } 

这样可以有效地使布局表格式化,而不需要将分区硬编码为HTML中的列。最后一条规则在每个第三个元素之后引起换行符有点棘手(但是有效)。

jsfiddle

附:这也会在最后一行图像下方创建一个20像素的边距。如果这是一个问题,您可以通过设置.gallery { margin-bottom: -20px }来取消它。

2
How about 2 divs, one for each row. Then set the margins on those. 

    <div class="row"> Your images or anchor tags</div> 
    <div class="row"> Your images or anchor tags</div> 

然后

.row{ 
     margin-top:10px; 

    } 

或不过多的空间你想要的图像的行之间。

您可以使用div来显示图像,以便更好地将它们放置在屏幕上。特别要避免为定位标记添加边距。

div.img{ 
    display:inline; 
} 

.firstcol{ 
    margin-left:15px; 
} 

.col{ 
    margin-left:10px; 
} 

<div class="img firstcol">The first image of teh row</div> 
<div class="img col">The second image of teh row</div> 

+0

看起来它会部分工作。我希望盒子边缘和图像之间的第一个空间为15,然后下一个空间为10。喜欢:| 15图像10图像10图像15 | – William

+0

然后创建几个类。根据您想要的空间大小,将它们称为row15,row10等。然后在需要时应用它们。 –

+0

这不是行,它是列,不是吗?该行在左侧为15px空间,然后在图像1和2之间为10px,在图像2和3之间为10px。然后出现新行。 – William

0

这是我得到的工作:

.row { 
    margin-left:20px; 
} 
.space { 
    margin-left:12px; 
    display: inline; 
} 
.row-space { 
    margin-bottom:20px; 
} 

div class=row 
    a href=x img 
    div class=space /div 
    a href=x img 
    div class=space /div 
/div 

div class=row-space /div 

我所需要的显示直列避免换行。过去我已经阅读并使用过float:left,但是这有一些副作用,这对于这个目的不是很好。

相关问题