我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..
我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..
当前回答
easy
img {
transform: translate(50%,50%);
}
其他回答
来,试试这个。
.parentdiv { 身高:400 px; 边框:2px实心#cccccc; 背景:# efefef; 位置:相对; } .childcontainer { 位置:绝对的; 左:50%; 上图:50%; } .childdiv { 宽度:150 px; 身高:150 px; 背景:lightgreen; 这个特性:50%; 边框:2px纯绿色; margin-top: -50%; margin-left: -50%; } < div class = " parentdiv”> < div class = " childcontainer”> < div class = " childdiv”> < / div > < / div > < / div >
你可以用下面的代码水平和垂直地居中一个图像(在IE/FF中工作)。 它会将图像的上边缘放置在浏览器高度的50%,而margin-top(向上拉图像高度的一半)将完美地居中。
<style type="text/css">
#middle {position: absolute; top: 50%;} /* for explorer only*/
#middle[id] {vertical-align: middle; width: 100%;}
#inner {position: relative; top: -50%} /* for explorer only */
</style>
<body style="background-color:#eeeeee">
<div id="middle">
<div id="inner" align="center" style="margin-top:...px"> /* the number will be half the height of your image, so for example if the height is 500px then you will put 250px for the margin-top */
<img src="..." height="..." width="..." />
</div>
</div>
</body>
我有一个图片库,我不知道准确的高度或宽度的图像之前,我只知道他们是小于div,他们将被包含。
通过在容器上组合行高设置并在图像元素上使用vertical-align:middle,我最终使用以下HTML标记和以下CSS使其在FF 3.5、Safari 4.0和IE7.0上工作。
HTML标记
<div id="gallery">
<div class="painting">
<a href="Painting/Details/2">
<img src="/Content/Images/Paintings/Thumbnail/painting_00002.jpg" />
</a>
</div>
<div class="painting">
...
</div>
...
</div>
CSS
div.painting
{
float:left;
height:138px; /* fixed dimensions */
width: 138px;
border: solid 1px white;
background-color:#F5F5F5;
line-height:138px;
text-align:center;
}
div.painting a img
{
border:none;
vertical-align:middle;
}
这是一种老式的解决方案,但浏览器市场份额已经足够大了,如果你不担心IE7的性能下降,你可能不需要IE黑客的部分。当你知道外部容器的尺寸,但可能知道也可能不知道内部图像的尺寸时,这种方法是有效的。
.parent {
display: table;
height: 200px; /* can be percentages, too, like 100% */
width: 200px; /* can be percentages, too, like 100% */
}
.child {
display: table-cell;
vertical-align: middle;
margin: 0 auto;
}
<div class="parent">
<div class="child">
<img src="foo.png" alt="bar" />
</div>
</div>
div { position: absolute; border: 3px solid green; width: 200px; height: 200px; } img { position: relative; border: 3px solid red; width: 50px; height: 50px; } .center { top: 50%; left: 50%; transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); /* IE 9 */ -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */ } <div class="center"> <img class="center" src="http://placeholders.org/250/000/fff" /> </div>
相关:居中图像