Video Tutorial:
If you would prefer to learn by watching a video tutorial rather than reading this blog post you should check out this video down below. Also, subscribe to my youtube channel where I post new tutorials every alternate day.
Project Folder Structure:
Before we start coding let us take a look at the project folder structure. We create a project folder called – ‘Styling Broken Images’. Inside this folder, we have two files. These files are index.html and style.css.
HTML:
We begin with the HTML code. In the HTML code, you just have to add some value to the alt attribute and add a class name called – ‘broken-images’ to all the images.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Style Broken Images</title> <!-- Stylesheet --> <link rel="stylesheet" href="style.css" /> </head> <body> <img src="trainn.jpg" alt="train" class="broken-img" /> </body> </html>
CSS:
We then use CSS to display a text each time any image with the class name – ‘broken-images’ is broken. The text and styling will be hidden if the image is available.
body { background-color: #1c64f6; } .broken-img { font-size: 1.25em; width: 40%; min-width: 22em; position: absolute; /* Just For Centering Purpose*/ transform: translate(-50%, -50%); left: 50%; top: 50%; } /* This will be display only if the image is broken */ .broken-img:before { position: absolute; content: "\01F614 Sorry! The "attr(alt) " image is broken"; background-color: #ffffff; font-family: "Poppins", sans-serif; font-size: 0.9em; left: 0; top: 0; width: 100%; padding: 1em 0; text-align: center; border: 3px dashed #afb3e5; box-shadow: 0 0 0 0.45em #ffffff, 0 1.2em 3.6em rgba(1, 7, 60, 0.3); border-radius: 0.2em; }
That’s it for this tutorial. If you face any issues while creating this code you can download the source code by clicking on the download button below. Also if you have any queries, suggestions or feedback comment below.
Happy Coding!