Reputation: 471
I was wondering if there was anyway I could position an image based on the browser's width and height within a HTML file. I know if I wanted to change an image's width/height, I could do something like this:
<script>
alert("Width is " + window.outerWidth + " height is " + window.outerHeight);
var canvas = document.getElementsByTagName('img')[0];
canvas.width = 200;
</script>
Is there anything similar I can do for positioning an image at a specific location, based on the browser width and height. Ideally, a way that does not include media queries if possible!
Thanks!!
Upvotes: 2
Views: 63
Reputation: 20359
To position an image based on the browser's width and height, give it an id
to target it in CSS. Then use that id
to give it an absolute position, and use the vw
and vh
units to position it. Each 1vw
is 1% of the window's width, and each 1vh
is 1% of the window's height:
HTML:
<img id="myImg" src="http://i.imgur.com/5LGqY2p.jpg?1">
CSS:
#myImg {
position: absolute;
left: 20vw;
top: 10vh;
}
In this example, the top left corner of your image will be 20% of the way from the left of the screen, and 10% of the way down from the top of the screen.
Read more about CSS units here: https://css-tricks.com/the-lengths-of-css/
Upvotes: 1