关于图像对齐的简单css问题

时间:2011-04-14 20:57:31

标签: css

我想将我的图片与此页面对齐:http://nymanssnickeri.se/

我的内容div是900px宽。如您所见,图像#1和#3位于内容div的边缘。在此页面上,边距仅用于中间的图像。如果没有超过3个图像,我可以在第一个图像上使用第一个孩子选择器,问题将得到解决。但有时会有多行图像。有什么想法如何以一种好的方式实现这一目标?感谢

4 个答案:

答案 0 :(得分:0)

您可以为每个图像提供相等的水平边距,然后在第一个和最后一个图像上添加一个类,分别包含margin-left: 0margin-right:0。为了做到这一点,你必须使用边距大小/数学。

示例:

#container img { margin: 0 20px; }
#container img.first {margin-left: 0; }
#container img.last {margin-right: 0; }

20px只是我选择的随机数。这取决于你的图像大小,以及你有多少。

编辑:

边距的数学(检查一下,只需动起来):

(总容器宽度 - 所有图像的总宽度)/(图像总数 - 1)* 2

答案 1 :(得分:0)

如果提前知道布局,包括照片数量等。您可以使用表格:

<table width="900"><tr><td><img /></td><td><img /></td>
<td><img /></td></tr></table>

或者您可以使用div,并将它们连接起来以创建多行:

<style
div#img-container { width: 900px; }
div#img-container img { display: block; }
img.lft { float: left; }
img.mid { margin: 0 auto; }
img.rgt { float: right; }
</style>
<div id="img-container">
<img class="lft"/>
<img class="mid"/>
<img class="rgt"/>
<br />
</div>

您可能需要在图像上将边距,填充和边框重置为0才能使用此方法,否则图像会略微溢出并且无法正确对齐。

答案 2 :(得分:0)

如果您希望每行有三个图像,而不必担心设置像素边距以达到效果,您可以执行以下操作......

演示:http://jsfiddle.net/ENQTZ/1/

<div>
    <span class="a"></span>
    <span class="b"></span>
    <span class="c"></span>
</div>
<div>
     <span class="a"></span>
     <span class="b"></span>
     <span class="c"></span>
 </div>

div {
    text-align: center;
    margin-bottom: 20px;
}
span {
    display: block;
    width: 32%;
    height: 100px;
    background-color: red;
}
.a {
    float: left;
}
.b {
    float: right;
}
.c {

     margin-left: auto;
     margin-right: auto;
     position: relative;
     left: 0px;
     top: 0px;
}

答案 3 :(得分:-1)

<center> 
<div ID="Content" Style="Width:900px"> 
  <center>
     <table>
        <tr>
           <td>
              Your image here
           <td>
           <td>
              Your image here
           <td>
        </tr>
        <tr>
           <td>
              Your image here
           <td>
           <td>
              Your image here
           <td>
        </tr>
     </table>
  </center>
</Div>
</center>

这对你有用吗?这是我使用的模板。只需为更多单元格添加更多td标记,为更多行图像添加更多tr标记。

此外,您可以将图像设置为所需的确切尺寸,但要小心拉伸/挤压可能会发生

<img ID="Image" src="Image/Cat.png" alt="Cat.png" style="Width:50px;Height:50px" />
相关问题