position image at bottom of div without wrapper
How would I position an image at the bottom of a div using JavaScript without wrapping it? I understand I can wrap it with a div and do absolute positioning, but that muddies up the markup and it's dynamic content too, so I can't wrap the image, it has to 开发者_开发技巧target an image in a specific div.
Here is the basic markup, need it to find height of div, then position image at bottom. i think that is how it would work?
<div id="content">
<p>some text</p>
<img src="img.jpg"/>
</div>
You can position an image as well to the bottom of a DIV, you don’t need to add a second wrapper. Either do it in CSS:
div { position: relative; }
div > img { position: absolute; bottom: 0; }
or do the same thing in JS if you need it be in JS.
As simple as this~~
#content
{ position:relative; padding-bottom:50px; } // if image height is 50px;
#content > img
{ position:absolute; bottom:0; }
That should do it. If you don’t use padding-bottom in the second rule, the image will be overflowed (and will cover the text) if the content of the div (its text) is not taller that the image height.
I would do it using CSS for sure, and don't recommend doing it this way.. but you can do it with JS like so
Live Demo
var image = document.getElementById("image"),
contentDiv = document.getElementById("content");
image.style.position = 'absolute';
image.style.top = contentDiv.offsetTop + contentDiv.offsetHeight - image.offsetHeight + 'px';
精彩评论