这是我的CSS课程:
.overitem {
position: relative;
background: url(images/bg.png) no-repeat;
width:83px;
height: 83px;
}
.sit {
position: absolute;
top: 50%;
left: 50%;
}
我的HTML:
<div class="overitem"><img src="/images/vcs.png" class="sit"/></div>
问题是我无法在img
类的背景中间的overitem
标记中创建。我该怎么办,让它出现在bg.png
图片的中间?
答案 0 :(得分:2)
由于.sit
类必须具有固定的宽度和高度(因为它是图像),因此可以使用以下方法:
.sit {
position: absolute;
top: 50%;
left: 50%;
width: 500px;
height: 500px;
margin-top: -250px; /* Half the height */
margin-left: -250px; /* Half the width */
}
来源:http://css-tricks.com/snippets/css/absolute-center-vertical-horizontal-an-image/
答案 1 :(得分:2)
您可以将边距设置为 1/2(“overitem”的宽度减去“sit”的宽度)和 1/2(“overitem”的高度“sit”的高度宽度) 或试试这个:
.sit {
position: absolute;
top: 50%;
left: 50%;
margin-left: -(HALF_OF_WIDTH_OF_IMAGE);
margin-top: -(HALF_OF_HEIGHT_OF_IMAGE);
}
答案 2 :(得分:1)
试试这个:
elems = document.getElementsByClassName('sit');
for( i = 0, j = elems.length; i < j; i++){
elems[ i ].style.marginLeft = ( elems[ i ].parentNode.offsetWidth - elems[ i ].offsetWidth ) / 2;
elems[ i ].style.marginTop = ( elems[ i ].parentNode.offsetHeight - elems[ i ].offsetHeight ) / 2;
}
答案 3 :(得分:1)
在.sit类中,你需要:
margin-left: -(half of width);
margin-top: -(half of height);
另一种选择是:
.overitem {
position: relative;
background: url(images/bg.png) no-repeat;
width:83px;
height: 83px;
line-height: 83px;
}
.sit {
vertical-align: middle;
}