Home > Article > Web Front-end > How to set the background image size in html
In web design, background images are an important visual element that can provide a better user experience and attract the user's attention. However, if the background image is not the right size, it may affect the overall aesthetics and loading speed of the web page. In this article, we will learn how to use HTML to set the size of background images in order to optimize the appearance and performance of your web pages.
Using a CSS style sheet is the easiest way to set the size of a background image. In HTML, we can use the <style> tag to embed a CSS style sheet into a web page, and then set the width and height for the background image.
Here is an example:
<!DOCTYPE html> <html> <head> <style> body { background-image: url('background.jpg'); background-size: 100% 100%; } </style> </head> <body> <h1>Hello, World!</h1> </body> </html>
In the above code, we embed the CSS style sheet into the <style>
tag. We set the background image for the body
element and use the background-image
attribute to specify the URL of the image. We then set the image size to 100% width and 100% height using the background-size
property.
When we open a web page, the background image will automatically fill the entire screen.
Another way to set the size of the background image is to use the style## of the
tag #Attributes.
Here is an example:
<!DOCTYPE html> <html> <head> </head> <body style="background-image: url('background.jpg'); background-size: cover;"> <h1>Hello, World!</h1> </body> </html>In this example, we set the
style attribute directly in the
tag. We specify the background image as the value of the
background-image property and use the
background-size property to set the image size to cover the entire screen.
Using this method, we can quickly set the size of the background image, but the disadvantage of this method is that it is not as flexible as controlling it through a style sheet.
<!DOCTYPE html> <html> <head> <style> body { background-image: url('background.jpg'); } </style> <script> window.addEventListener('scroll', function() { var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; var body = document.querySelector('body'); body.style.backgroundSize = (100 + scrollTop / 5) + '%'; }); </script> </head> <body> <h1>Hello, World!</h1> </body> </html>In this example, we added a