如何在垂直和水平方向上定位中心/中间的图像

时间:2011-02-03 15:33:34

标签: html css

<div id="photo_leftPanel" style="float: left; width: 604px; position: relative;">
<img src="bla.jpg">
</div>

如何让图像从此框的中间开始? (中间垂直和水平)

6 个答案:

答案 0 :(得分:33)

有几种方法可以做到这一点,如果它需要在所有浏览器(IE7 +和其他浏览器)中工作,你需要做一些不同的事情,以使其在某些情况下有效。

  1. 使用绝对位置。仅当您知道图像的大小时才有效。 在这里,您将其设置为position: absolute; left: 50%; top: 50%; margin: -<half height of image> 0 0 -<half width of image>

    请参阅此处的示例:http://jsfiddle.net/JPch8/

  2. 使用margin: 0 auto;text-align: center;line-height/font-size。 这有点棘手,因为对于像图像这样的内联块元素,行高不能像IE那样工作。这就是font-size的用武之地。 基本上,您将图像容器的行高设置为与容器的高度相同。这将垂直对齐内联元素,但在IE中,您需要设置字体大小,以使其工作。

    请参阅此处的示例:http://jsfiddle.net/JPch8/2/

  3. 在支持display: flex的现代浏览器中,只需将容器div设置为display: flex; align-items: center; justify-content: center;

    即可

    请参阅此处的示例:https://jsfiddle.net/ptz9k3th/

答案 1 :(得分:1)

将图片放入$str = '19a smith STREET'; echo preg_replace_callback('~(\d+[a-z]?)(\s+.*)~', function ($matches) { return strtoupper($matches[1]) . ucwords(strtolower($matches[2])); }, $str); <div>,而不指定框的大小

text-align:center;

或者,您可以指定<div class="picture_div" style="margin:0px auto; text-align:center;"> <img src="media/BezierCurve.gif" /> </div> 框的widthheight以使图像居中(实际上是div框)。

<div>

答案 2 :(得分:0)

float:left; position:relative”可能无法按预期工作。浮动元素被认为是绝对的。

要使图像垂直居中,你需要在div上有一个高度,你的父母需要高度。 (垂直居中是一种痛苦)。如果这些是您唯一的元素,那么下面的示例将起作用,但要注意容器上的height: 100%可能会影响您的布局的其余部分。

<html>
<head><title></title>
<style type="text/css">
html, body { 
     height: 100%;
}

#photo_leftPanel {
     height: 500px; /*guessing*/
     width: 604px;
     float: left;
}

#photo_leftPanel img {
     margin: auto;
     vertical-align: middle;
}
</style>
</head>
<body>
<div id="photo_leftPanel">
<img src="bla.jpg" />
</div>
</body>
</html>

答案 3 :(得分:0)

flexbox是现代浏览器的合适解决方案。可以将flex容器配置为在水平和垂直方向上对齐其项目。

<div style="display: flex; align-items: center; justify-content: center; width: 600px; height: 600px;">
    <img src="bla.jpg">
</div>

答案 4 :(得分:0)

HTML:

<div id="photo_leftPanel">
   <img src="bla.jpg">
</div>

CSS:

div.photo_leftPanel {
   position: relative;
}

div.photo_leftPanel > img {
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
}

答案 5 :(得分:-2)

我希望我理解你想要达到的目标。

<div id="photo_leftPanel" style="float: left; width: 604px; position: relative;">
<center><img src="bla.jpg" style="vertical-align:middle;"></center>
</div>
相关问题