使用绝对定位在内容上方显示图像

display an image above the content using absolute positioning

本文关键字:方显示 显示 图像 定位      更新时间:2023-11-20

我只是想知道如何使用绝对定位在<p/>上方显示图像。注意:图像没有定义高度,可以更长也可以更短。目标是使用绝对定位在上方显示图像。

<div id="wrap">
    <p>Hello</p>
</div>
<script>
    //Display an image above the <p/> using absolute positioning.
        //Note: the image has no define height, it could be longer or shorter. The goal is to 
         display the image above the <p/> using absolute positioning.
</script>

如果您想要<img>高于<p>,是否有原因不能执行以下操作?

<div id="wrap">
    <img src="path/to/img">
    <p>Hello</p>
</div>

我强烈推荐这种方法,因为图像的高度或宽度不会破坏任何东西,并且<p>会根据其大小移动。

但让我们假设<img>在其他地方,比如下面的

<div id="wrap">
    <p>Hello</p>
    <img src="path/to/img">
</div>

您可以添加以下CSS:

img {
    position: relative:
    top: -25px;
}

不过,这不是一件很好的事情,因为它实际上只是将图像上移了25个像素。如果段落<p>的大小发生变化怎么办?如果您在<p>段的上方添加更多内容,该怎么办?

您也可以尝试:

img {
    position: fixed;
    top: 0;
}

这将使图像始终处于视口的顶部。同样,使用这两种position方法中的任何一种都会带来很多问题(除非这是您想要的),我建议我的第一个建议是使用纯HTML,并避免CSS位置修复。

我看不出有什么聪明的方法可以做到这一点。。。为什么不$("#wrap").bfore("image");没有绝对地位?

如果你的意思是隐藏,那就是:

标记

<div class="wrapper">
  <p>I will be hidden soon.</p>
</div>

CSS

.wrapper img{
  position:absolute;
  top: 0;
}

JS

$('.wrapper').append($('<img>', { src : 'http://placehold.it/350x150'}));

参见fiddle