简体   繁体   中英

display an image above the content using absolute positioning

I am just wondering how to 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 using absolute positioning.

<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>

If you want an <img> above the <p> , is there a reason why you can't do the following?

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

I would highly recommend this approach as the height or width of the image will not break anything and the <p> will move according to it's size.

But let's assume the <img> is elsewhere, like below it:

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

You can add the following CSS:

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

This is not a very good thing to do, though - as it literally just moves the image up 25 pixels. What if the size of the paragraph <p> changes? What if you add more content above the paragraph <p> ?

You can also try:

img {
    position: fixed;
    top: 0;
}

This will put the image at the top of the viewport at all time. Again, using either of the these position methods present a lot of problems (unless it's what you want) and I recommend my first suggestion using pure HTML, and avoiding CSS position fixes.

I see no smart way to do this... why not $("#wrap").before("image"); without absolute position?

If you mean in terms of hiding, there you go:

Markup

<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'}));

See fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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