2014-01-10 153 views
1

我想居中这4个图像。水平它正在工作,但垂直它不会工作。有谁知道如何解决这个问题?目前我有一个黑色的页眉/页脚部分,4个图像水平居中。一切都是可扩展的,但不是图像的高度。定位垂直中心

我做得对吧?

HTML:

<section> 
    <div class="pic"> 
     <img src="img.png" alt="Pic" /> 
    </div> 
    <div class="pic"> 
     <img src="img.png" alt="Pic" /> 
    </div> 
    <div class="pic"> 
     <img src="img.png" alt="Pic" /> 
    </div> 
    <div class="pic"> 
     <img src="img.png" alt="Pic" /> 
    </div> 
</section> 

CSS:

body { 
    margin:0; 
    padding:0; 
    max-width: 100%; 
    max-height:100%; 
} 
section { 
    position:absolute; 
    top:5%; 
    bottom:5%; 
    left:0; 
    width:100%; 
    height:90%; 
} 
section img { 
    width:12.5%; 
    float:left; 
    margin-left:10%; 
} 
+1

是否型材件需要有90%的高度? – j08691

+0

@ j08691我认为这是因为页眉/页脚总高度为10% –

+0

是啊,页眉和页脚5%所以第90%部分 – Nick

回答

0

我认为它更容易包裹的图像在一个容器中,然后中心集装箱容器的父,在这种情况下,你可以使用一个商品标签包装的图像的再中心在这样的节文章

HTML

<section> 
    <article> 
     <div class="pic"> 
      <img src="img.png" alt="Pic" /> 
     </div> 
     <div class="pic"> 
      <img src="img.png" alt="Pic" /> 
     </div> 
     <div class="pic"> 
      <img src="img.png" alt="Pic" /> 
     </div> 
     <div class="pic"> 
      <img src="img.png" alt="Pic" /> 
     </div> 
    </article> 
</section> 

CSS

html, body { 
    height: 100%; 
    width: 100%; 
} 

section { 
    top: 5%; 
    left: 0%; 
    width: 100%; 
    height: 90%; 

    /* strech */ 
    overflow: hidden; 
} 

article { 
    width:80%; 
    height:40%; /* change this to set height */ 

    /* CSS absolute center begin */ 
    border: 2px solid #0000ff; 
    margin: auto; 
    position: absolute; 
    display: inline-block; 

    top: 0; 
    bottom: 0; 
    left:0; 
    right:0; 
    /* CSS absolute center end*/ 
} 

.pic { 
    position: relative; 
    float: left; 
    width: 12.5%; 
    height: 100%; 
    margin-left: 10%; 
} 

.pic img{ 
    position: relative; 
    width:100%; 
    height:100%; 
} 

希望它可以帮助你

+1

它很有效,谢谢。需要调整拉伸,但没关系。谢谢 – Nick

1

假设图像的宽度等于图像的高度(比如你给的代码了),你可以只使用margin-top50% - imageHeight 。这看起来就像

section img { 
    width:12.5%; 
    margin-top:32.5%; 
    float:left; 
    margin-left:10%; 
} 

Demo

如果他们没有,你可以使用this pure CSS approach

+0

对不起,但图像的高度与宽度不一样 – Nick

+0

@ user2438434添加一个替代方案 –

+0

好的,将会看一看 – Nick

0

,您可以给部分position:relative;,然后做与图像一招。

下面的示例使它们位于该部分的中心,如果要将图像展开,但是垂直对齐,则需要对包含元素执行此技巧(例如在部分中的图像周围跳转:

section { 
    position:relative; 
    top:5%; 
    bottom:5%; 
    left:0; 
    width:100%; 
    height:90%; 
} 
section img { 
    /*width:12.5%; 
    float:left; 
    margin-left:10%;*/ 
    position:absolute; 
    top:50%; 
    margin-top:-25%;/* should be half the height of the image */ 
    left:50%; 
    margin-left:-25%;/* should be half the width of the image */ 
} 
+0

你不能同时使用'top'和'bottom'值,只有'bottom'值被使用。此外,这将定位所有四个图像在相同的位置,而不是在 –

+0

之间的空间噢,谢谢 – Nick

+0

@ ZachSaucier正确,我忘了清理OP的代码。是的,这是一个垂直和水平中心的例子,如答案中所示。要放在两者之间,需要添加一个元素。您的答案通常会更好,因此我选择了它;-) –