简体   繁体   English

图像(绝对位置)在相对位置的容器中水平居中

[英]Image(Absolute Positioned) Horizontally center in a Relative Positioned container

I want to center an absolute positioned image horizontally in a relative positioned container. 我想在相对位置的容器中将绝对位置的图像水平居中。 I tried to do with css . 我试着用CSS做。 But I could't and i did in Jquery 但是我做不到,我在Jquery做到了

http://jsfiddle.net/CY6TP/ [This is i tried to do in Jquery] http://jsfiddle.net/CY6TP/ [这是我在Jquery中尝试做的]

**Guys can anyone help me to do this in CSS.**

Thanks in advance 提前致谢

try this: 尝试这个:

var width=$('.main').width();
var height=$('.main').height();


$('a').css(
{
"position":"absolute",
"bottom":"50%",
"margin-top":(height/2),
"left":(width/2)-50

});

DEMO 演示

UPDATE 更新

In CSS 在CSS中

.main a{
   bottom:50%;
    margin-top:-150px;   
    position:absolute;
    left:75px;
}

DEMO 演示

You can set all in css like this : 您可以像这样在css中设置所有内容:

a{
position : absolute ;
height : 10px;
width : 100px;
top : 50%; 
margin-top : -5px;
left : 50%; 
margin-left : -50px;}

Demo 演示版

try this to make it horizontally center 试试这个,使其水平居中

a{
    position: absolute;
    text-align: center;
    width: 100%;
}

OR this to make it horizontally and vertically both center 或使其在水平和垂直方向上都居中

a {
    height: 100%;
    position: absolute;
    text-align: center;
    top: 50%;
    width: 100%;
}
.main img { top:50%; left:50%; margin: -11px 0 0 -50px; position: absolute;}

这是你想要的吗?

If your height is fixed, you could use something like this maybe? 如果您的身高是固定的,那么您可以使用类似的方法吗?

CSS: CSS:

#div1 {
    width:100%;
    height:100px;
    text-align:center;
}

#div1 img {
    line-height:100px;
}

HTML: HTML:

<div id="div1">
    <img src="yourimage.jpg" />
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM