[英]How can I horizontally and vertically center an <img> in a <div>?
I don't want to center a div, I want the contents of a div to be centered. 我不想以div为中心,我希望div的内容居中。 I would like horizontal and vertical alignment. 我想水平和垂直对齐。
Sorry, if this is too easy or whatever, but this is kind of a hassle to get it right. 对不起,如果这太容易或者其他什么,但这对于纠正它来说是一件麻烦事。
Grae GRAE
I am using IE7 我正在使用IE7
If you know the height and width of your image, position it absolutely, set top/left to 50% and margin-top/left to negative half the height/width of your image. 如果你知道你的形象的高度和宽度,它定位绝对,机顶盒/左到50%,边距/左负一半的高度/图像宽度。
#foo {
position:relative; /* Ensure that this is a positioned parent */
}
#foo img {
width:240px;
height:200px;
position:absolute;
left:50%;
top:50%;
margin-left:-120px;
margin-top:-100px;
}
Live example: http://jsfiddle.net/Zd2pz/ 实例: http : //jsfiddle.net/Zd2pz/
I know you've said that dont want to center a div but to achieve your requirement in a cross browser way would be easier using a jquery plugin and a fake div that contains your element to be centered. 我知道你已经说过不想以div为中心,但是以跨浏览器的方式实现你的需求会更容易使用jquery插件和包含你的元素的假div。
I have successfully centered almost anything using this very small plugin that can center any block element. 我已经使用这个非常小的插件成功地集中了任何东西,可以将任何块元素居中。
The only other way I know are the answer that you already received from @simshaun & @Prhogz 我知道的另一种方式是你已经从@simshaun和@Prhogz收到的答案
EDIT: As per comment request 编辑:根据评论请求
Include the script in your head tag 在脚本标记中包含脚本
<script type="text/javascript" src="<%: Url.Content( "~/_assets/js/jquery.center.min.js" )%>"></script>
Now if you have a DIV that you want to center inside your markup simply use it as 现在,如果您有一个想要在标记中居中的DIV,只需将其用作
$(document).ready(function() {
$("#myDIV").center({ vertical: false });
});
although the following is obsolete , it still works for almost all browsers 虽然以下内容已经过时 ,但它仍适用于几乎所有浏览器
<center>
<div>
your html
</div>
</center>
however, visit this link 但是,请访问此链接
http://www.110mb.com/forum/vertical-horizontal-alignment-of-image-within-div-t31709.0.html http://www.110mb.com/forum/vertical-horizontal-alignment-of-image-within-div-t31709.0.html
For horizontal alignment, use text-align:center;
对于水平对齐,请使用text-align:center;
For vertical alignment, see for example the W3 style guide 有关垂直对齐的信息,请参阅W3样式指南
If you know the inner element's height beforehand, 如果事先知道内部元素的高度,
CSS: CSS:
.container {
text-align: center; /* Center horizontally. */
/* For demo only */
border: 1px solid #000;
height: 500px;
margin: 20px;
width: 700px;
}
.container img {
margin-top: -167px;
position: relative;
top: 50%;
}
HTML: HTML:
<div class="container">
<img src="http://farm6.static.flickr.com/5004/5270561847_7223069d5e.jpg" width="500" height="334" alt="">
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.