放置一个图像到右上角-CSS

我需要在 div 的右上角显示一个图像(图像是一个“对角线”色带) ,但是保持当前文本包含在一个内部 div 中,就像粘在它的顶部一样。

我尝试了不同的方法,比如将图像包含到另一个 div 中,或者定义它的类,比如:

.ribbon {
position: relative;
top: -16px;
right: -706px;
}


<div id="content">
<img src="images/ribbon.png" class="ribbon"/>
<div>some text...</div>
</div>

但是运气不好。我得到的最好的结果是所有的文本都向下滚动了相同的高度尺寸的图像。

知道吗?

470809 次浏览

你可以这样做:

<style>
#content {
position: relative;
}
#content img {
position: absolute;
top: 0px;
right: 0px;
}
</style>


<div id="content">
<img src="images/ribbon.png" class="ribbon" alt="" />
<div>some text...</div>
</div>

相对地定位 div,并将带子绝对地定位在它里面。比如:

#content {
position:relative;
}


.ribbon {
position:absolute;
top:0;
right:0;
}

在研究同一个问题时,我发现了一个例子

<style type="text/css">
#topright {
position: absolute;
right: 0;
top: 0;
display: block;
height: 125px;
width: 125px;
background: url(TRbanner.gif) no-repeat;
text-indent: -999em;
text-decoration: none;
}
</style>


<a id="topright" href="#" title="TopRight">Top Right Link Text</a>

这里的技巧是创建一个小的(我使用的是 GIMP) PNG (或 GIF) ,它有一个透明的背景,(然后只需删除相反的底部角落。)

尝试使用 float: right;和一个新的 div 作为顶部,这样图像将保持在顶部。

例如:

#left{
float: left;
}
#right{
float: right;
}
<div>
<button type="button" id="left" onclick="alert('left button')">Left</button>
<img src="images/ribbon.png" class="ribbon" id="right">
</img>
</div>
<p>some text...
the image is on the top right corner</p>
<p>some more text...</p>