2014-10-11 51 views
1

首先,不知道这是否是相关的或没有,但我使用引导3.图像的位置是:绝对没有父DIV中与中心的位置是:相对

所以对于我的网页的这一部分(还有更多在它下面)我有视口高度设置为100,并在里面它是两行,每个占据该视口的50%。在第一行是一个图像,我试图水平和垂直居中。在第二行是一个图像,我试图水平居中并固定在底部。在HTML看起来像这样:

<div class='row vh-100'> 
 
    <div class='col-xs-12 col-sm-12 col-md-12 col-lg-12 height-100'> 
 

 
     <!-- tats --> 
 
     <div class='row height-50'> 
 
      <div class='col-xs-12 col-sm-12 col-md-12 col-lg-12 relative height-100'> 
 
       <img src='images/logo.png' 
 
        class='img-responsive block absolute center middle max-height-100'> 
 
      </div> 
 
     </div> 
 

 
     <!-- silhouette --> 
 
     <div class='row height-50'> 
 
      <div class='col-xs-12 col-sm-12 col-md-12 col-lg-12 relative height-100'> 
 
       <img src='images/silhouette.png' 
 
        class='img-responsive block absolute center bottom max-height-100'> 
 
      </div> 
 
     </div> 
 

 
    </div> 
 
</div>

而CSS是这样的:

.block{ 
 
\t display: block; 
 
} 
 

 
.absolute{ 
 
\t position: absolute; 
 
} 
 

 
.relative{ 
 
\t position: relative; 
 
} 
 

 
.vh-100{ 
 
\t height: 100vh; 
 
} 
 

 
.vh-50{ 
 
\t height: 50vh; 
 
} 
 

 
.height-100{ 
 
\t height: 100%; 
 
} 
 

 
.height-50{ 
 
\t height: 50%; 
 
} 
 

 
.center{ 
 
    margin-left: auto; 
 
    margin-right: auto; 
 
} 
 

 
.top{ 
 
\t top: 0%; 
 
} 
 

 
.middle{ 
 
\t top: 50%; 
 
} 
 

 
.bottom{ 
 
\t bottom: 0%; 
 
} 
 

 
.max-height-100{ 
 
\t max-height: 100%; 
 
}

那么我现在运行到是这样的:既不是图像中心水平,除非我改变他们的立场相对。此外,第一个图像在整个页面内部垂直居中,而不是其中包含的div。任何想法?

回答

2

绝对位置的元素都集中这样的:

#element { 
left:50%; 
top:50%; 
transform:translate(-50%,-50%); 
} 

(不要忘记加上厂商的变换:-webkit-变换等)

此外,如果你知道的宽度绝对的元素,你可以使用:

margin-left:-halfelemwidth; 
margin-top:-halfelemheight; 

这将对于不支持CSS的老版本浏览器的支持帮助转换

编辑:输入时太累了,在用户的注意下,边缘顶部和边距应该是一半而不是全部。

edit2:你也可以试试这种方法。

对于具有高度使用元件:

display:table-cell; 
vertical-align:middle; 
text-align:center; 

这可以居中图像,而不离开容器,并且在不相对和绝对元素。

+1

应该可能是'margin-left: - (半角)' – 2014-10-11 19:14:26

+0

谢谢!这解决了水平居中问题。但是,整个页面的顶部图像仍然垂直居中。它应该在上半部分垂直居中,因为它的父元素只占用了页面的50%。 – user3630824 2014-10-11 19:18:11

+0

也将编辑为垂直。 – scooterlord 2014-10-11 19:24:24