我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..
我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的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>
相关:居中图像
其他回答
垂直对齐是最常被误用的css样式之一。对于不是td或css“display: table-cell”的元素,它不能像你期望的那样工作。
这是一篇关于这个问题的很好的文章。http://phrogz.net/CSS/vertical-align/index.html
实现你想要的目标最常见的方法是:
填充上/下 绝对位置 行高
这有点晚了,但这里有一个解决方案,我用垂直对齐元素在一个父div。
当您知道容器div的大小,但不知道包含的图像的大小时,这是有用的。(这是在使用灯箱或图像旋转木马时经常出现的情况)。
以下是你应该尝试的发型:
container div
{
display:table-cell;
vertical-align:middle;
height:200px;
width:200px;
}
img
{
/*Apply any styling here*/
}
使用定位。下面的方法对我很有效:
div{
display:block;
overflow:hidden;
width: 200px;
height: 200px;
position: relative;
}
div img{
width: 50px;
height: 50px;
top: 50%;
left: 50%;
bottom: 50%;
right: 50%;
position: absolute;
}
你可以使用以下属性轻松做到这一点:
#内容{ 显示:flex; 对齐项目:中心; 宽度:200 px; 身高:200 px; 边框:1px纯红色; } # myImage { 显示:块; 宽度:50 px; 高度:50 px; 保证金:汽车; 边框:1px纯黄色; } < div id = "内容" > <img id="myImage" src="http://blog.w3c.br/wp-content/uploads/2013/03/css31-213x300.png"> < / div >
引用:W3
我喜欢跳老式马车!
以下是这个答案在2015年的更新。我开始使用CSS3 transform来做我的定位工作。这允许你不需要做任何额外的HTML,你不需要做数学(找到半宽的东西),你可以在任何元素上使用它!
这里有一个例子(最后是小提琴)。HTML:
<div class="bigDiv">
<div class="smallDiv">
</div>
</div>
附带CSS:
.bigDiv {
width:200px;
height:200px;
background-color:#efefef;
position:relative;
}
.smallDiv {
width:50px;
height:50px;
background-color:#cc0000;
position:absolute;
top:50%;
left:50%;
transform:translate(-50%, -50%);
}
我最近经常做的就是给我想居中的东西一个类然后每次都重用这个类。例如:
<div class="bigDiv">
<div class="smallDiv centerThis">
</div>
</div>
css
.bigDiv {
width:200px;
height:200px;
background-color:#efefef;
position:relative;
}
.smallDiv {
width:50px;
height:50px;
background-color:#cc0000;
}
.centerThis {
position:absolute;
top:50%;
left:50%;
transform:translate(-50%, -50%);
}
通过这种方式,我将始终能够将容器中的内容居中。你只需要确保你想居中的东西是在一个定义了位置的容器中。
这是小提琴
BTW:这也适用于在较小的divs中居中更大的divs。