[英]Place div on top of image that is centered
我有一个看起来像这样的标记:
<div style="width: 150px; height: 250px;">
<img src="Image1.jpg" />
<div class="YellowExclaimIcon iconsBlack"></div>
</div>
我要实现的目标如下:
这意味着图像应始终放置在父div的中心(水平和垂直),警告图标应位于图像顶部,右边和底部的边距为5。
还要注意的另一件事是,图像的宽度和高度并不总是相同的,但是警告图标的位置应始终位于正确的位置。
YellowExclaimIcon类包含背景图像,但是可以根据需要更改为图像。 要考虑的是图像还具有最大宽度和最大高度。
我在此线程CSS帮助中尝试了答案-div over image,但无法使其与居中配合使用。
如果图像的宽度和高度是可变的,则只有更改标记才能实现此目的,如下所示:
<style type="text/css">
div.container {
width:150px; height:250px; display:table-cell; vertical-align:middle;
text-align:center; background-color:#ededed}
div.image {
position:relative; display:inline-block; }
div.image img {
display:block; }
div.YellowExclaimIcon {
position:absolute; width:80px; height:80px; bottom:5px; right:5px;
background:transparent url(your-icon.png) no-repeat 100% 100%}
</style>
<div class="container">
<div class="image">
<img src="Image.jpg" alt="" />
<div class="YellowExclaimIcon"></div>
</div>
</div>
上面的示例将始终在水平和垂直方向上将图像居中对齐,并在右下角有一个图标,边缘为5px。
检查工作示例: http : //jsfiddle.net/Q9uhV/
使用position:relative
对于外格和absolute
于内的div
的HTML
<div class="outer">
<div class="YellowExclaimIcon"></div>
</div>
的CSS
.outer{
width: 150px; height: 250px;
border:solid red 1px;
position:relative;
vertical-align:middle;
background:url(http://icons.iconarchive.com/icons/everaldo/kids-icons/128/penguin-icon.png) no-repeat center center;
}
.outer img{text-align:center; vertical-align:middle}
.YellowExclaimIcon{
position:absolute;
width:100%;
height:100%;
top:0; left:0; background:url(http://da.countyofventura.org/images/buttons/images/warning-icon.gif) no-repeat center 95%;
}
您需要使用z-index和一些类似的定位:
<div style="width: 150px; height: 250px;">
<img src="Image1.jpg" style="z-index:-1" />
<div class="YellowExclaimIcon iconsBlack" style="z-index:1; margin-left:10px; margin-bottom:10px"></div>
</div>
例如,将边距设置为所需。
将警告图像设置为absolute
以便可以将其放置在指定位置的其他图像上。
HTML:
<div class="container">
<img src="penguin.png" />
<img class="warning" src="warning.png" />
</div>
CSS:
.warning {
position:absolute;
left:80px;
top:80px
}
请参阅此jsFiddle以获取演示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.