中心图像垂直和水平

时间:2013-05-22 22:52:44

标签: css

我倾向于在我设计的每个网站上都这样做,但我还没有真正找到一个真正好的方法来做到这一点。公司通常会向我提供他们的徽标,当您转到页面时,我将其置于屏幕中间,然后自动将您转到主页。我似乎无法找到一个好的方法来将图像置于屏幕中间,而不需要一堆表和div!有什么好建议吗?!

5 个答案:

答案 0 :(得分:5)

您可以尝试在HTML中使用div,如下所示:

<div id='dv'></div>

使用这样的背景图片:

#dv {
    background: url('http://pieisgood.org/images/slice.jpg') no-repeat 0 0;
    background-position: center;
}

html,body,#dv { /* so that the #dv can fill up the page */
    width:100%;
    height:100%;
}

Fiddle

答案 1 :(得分:1)

就个人而言,我喜欢使用display: table-cell方法。

例如,如果我的HTML是:

<div class="wrapper">
     <img src="http://placehold.it/150x50" alt="Company ABC" />
</div>

然后我的CSS应该是:

div.wrapper {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    width: 600px;
    height: 200px;
}

如果我无法使用上述方法,另一个可行的选择是使用line-height属性。

行高法的HTML:

<div class="wrapper">
    <img src="http://placehold.it/150x50" alt="Company XYZ" />
</div>

行高法的CSS:

img {
    line-height: 300px;
}

答案 2 :(得分:1)

您可以使用JavaScript计算中心点并使用margin或top(位置:relative / absolute)来定位它,但这不是很干净。

我假设你在谈论一个启动页面,所以这里有一个简单的例子(尽管在其他情况下我不建议像我一样修改body标签):

<!doctype html>
<html>
    <head>
        <title>blah</title>
        <style type="text/css">
            html,body {margin:0;padding:0;width:100%;height:100%;}
            body {display:table;}
            p {display:table-cell;text-align:center;vertical-align:middle;}
        </style>
    </head>
    <body>
        <p>Hello World - This could have an image in it</p>
    </body>
</html>

诀窍在于CSS:

  • 您希望水平和垂直居中的项目显示为表格单元格:display:table-cell
  • 您希望居中的项目的父级(容器)显示为表格:display:table
  • 确保表格显示元素占据了您想要居中的整个区域。
  • 必须告知您要居中的项目水平对齐(text-align:center声明)和垂直对齐(vertical-align:middle声明)
  • text-alignvertical-align属性仅以此特殊方式运行,因为该元素显示为table-cell

答案 3 :(得分:1)

您没有说图像尺寸是否已知。

有几种方法可以做到这一点,我赞成使用id="centreme"的图像(如果图像是200x200)和整个页面的包装

div#contentwrapper {
    width:100%;
    height:100%;
    position:relative;
}
img#centreme {
    position: relative;
    width: 200px;   /* the image width */
    height: 200px;  /* the image height */
    top: 50%;
    left: 50%;
    margin-top: -100px;  /* half the image height */
    margin-left:-100px;  /* half the image width */
}

让你玩http://jsfiddle.net/7PYzB/2/

答案 4 :(得分:1)

&#13;
&#13;
img {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%); /* IE 9 */
    -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */	    
}
&#13;
<body>
    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRMtBiLioXqfhufpptex_ta8kGJa5UDQS3aITpBetR8EwH5GGDTJw" />   
</body>
&#13;
&#13;
&#13;

相关:Center a div