Background Image Code

Background Image Element

Place after first body tag

	

<img id="background-image" src="path/to/my/image-file">
				

CSS

Place in style sheet. It sets the image position and hides the image until it has loaded and the javascript has run.

		

#background-image{
	z-index: -1;
	position: absolute;
	display: none;
}
	

Javascript

Place at bottom of of page inside the last body tag. Once the image has loaded it resizes the image and then makes the image visible. If the window is resized it resizes the image to fit within the viewport.

	
	
<script>		
const image = document.getElementById('background-image');
const html = document.getElementsByTagName('html')[0];

image.addEventListener("load", changeImagePosition);
window.addEventListener("load", changeImagePosition);
window.addEventListener('resize', changeImagePosition);

function changeImagePosition(){

	let viewportWidth = html.clientWidth;
	let viewportHeight = html.clientHeight;
	let viewportRatio = html.clientWidth / html.clientHeight;
	let imageRatio = image.naturalWidth / image.naturalHeight;
	let imageWidth;
	let imageHeight;
	let positionLeft;
	let positionTop;
	
	if(imageRatio < viewportRatio){
		image.style.height = viewportHeight + "px";
		image.style.width = "";	
	}else if(imageRatio > viewportRatio){
		image.style.width = viewportWidth + "px";
		image.style.height = "";	
	}else{
		image.style.width = "";
		image.style.height = "";
	}
		
	imageWidth = image.clientWidth;
	positionLeft = (viewportWidth - parseInt(imageWidth))/2;
	image.style.left = positionLeft + "px";

	imageHeight = image.clientHeight;
	positionTop = (viewportHeight - parseInt(imageHeight))/2
	image.style.top = positionTop + "px";
	image.style.visibilty = "visible";
	
}
</script>	






Georgia Website