How To Style Broken Images

The image has disappeared

I've lost the image

In this tutorial we're going to look at how you can customise broken images like the above to make them a bit more user friendly to the visitors of your site.

There are 3 methods that you can choose to use when customising broken images:

  • Alt attribute
  • CSS styling to make broken images look better
  • jQuery replace broken image

Alt Attribute

The first thing you need to do and the easiest way of adding some text to your images when they're broken is by using the alt attribute. This is used as a way of describing your images.

The alt attribute is useful for search engines as it gives them a way of understanding the context of the image along with the filename.

<img src="cantfindthisimage.com/image.jpg" alt="I've lost the image" />

CSS Styling

You can't style the way that the broken images look like but you can use pseudo-elements to create new elements that override the broken image styling with your own.

The default broken images will look like the below Image of stuff

It will automatically display the alt attribute with a broken image icon, there is a border around this which doesn't look great so we can start this by changing the styling to remove this border, like below.

Image of stuff

This is done by using :after to create a new element that sits on top of the broken image so we can style it however we want.

<img class="remove-border-broken-image" src="cantfindthisimage.com/image.jpg" alt="Image of stuff" />

First we need to add a position: relative to the image so that we can absolute position the :after element on top of the image.

img.remove-border-broken-image
{
    position: relative;
    width: 100%;
}

Then we add a :after element to the broken image this is absolute positioned so will be placed onto of the broken image. Using the content property we can pick up the alt attribute and display this on our new image.

img.remove-border-broken-image:after {
    content: attr(alt);
    font-size: 20px;
    display: block;
    position: absolute;
    z-index: 2;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #fff;
}

The next example shows how we can use the :before and :after pseudo element to fully customise how your images look.

Image of stuff

Start off by adding your broken image to the page.

<img class="styled-broken-image" src="cantfindthisimage.com/image.jpg" alt="Image of stuff" />

Next we're going to make the image full width and center the text so that the alt attribute text is placed in the middle of the image area.

img.styled-broken-image
{
    position: relative;
    width: 100%;
    display: block;
    text-align: center;
}

Using the :after pseudo element we can style the element to be a grey box area with the text being the image alt attribute followed by , please fix it! as a way of alerting the admin user of the site.

img.styled-broken-image:after
{
    content: attr(alt) ", please fix it!";
    font-size: 20px;
    display: block;
    position: absolute;
    z-index: 2;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: #ddd;
    height: 100%;
    padding: 3% 2% 3%;
    margin-bottom:2%;
    border: 2px dashed #999;
    cursor: pointer;
}

We can now use the :before pseudo to add a question mark to the box area to for additional styling to the image area.

img.styled-broken-image:before
{
    content: "?";
    display: block;
    position: absolute;
    z-index: 3;
    font-size: 40px;
    top: 15%;
    left: 0;
    right: 0;
    bottom: 0;
}

jQuery Replace Images

You can also use the jQuery solution and replace the image URLs with a broken image URL to have a placeholder for all your broken images.

Using the error event you can find all images that cause an error like 404 source not found.

$('img').on('error', function () {
    // do stuff to the broken images
});

What we can do is simply replace the broken images source to a placeholder image.

$('img').on('error', function (){
    $(this).prop('src', 'img/broken-image.png');
});

Or you have the option to simply hide them from the page.

$('img').on('error', function (){
    $(this).hide();
});

In a recent project I needed to automatically assign a image to a post from a URL. This situation happened where I had a library of image URLs which on the publish event of a new WordPress post we needed to check that the post had a featured image, if it didn't have a featured image then we automatically assign a image to this post.

Therefore I had an array of image URLs we will use to randomly select an image to use as the featured image on the post. To programmatically assign an image to a post as the featured image you need to use the function set_post_thumbnail(), which takes two parameters a post ID and the attachment ID.

set_post_thumbnail( $postId, $attachmentId );

In WordPress a image that is added to the media library is called an attachment, so to add an image as the featured image on a post it first needs to be added to the media library before we can assign it to a post. In this situation I know that all the images in the array are added to the media library we just need to get the attachment ID to assign it to the post.

When an image is added to the media library it's classed as a attachment, which is added to the wp_posts table with a post type of attachment. This means to get the ID of the image we can simply query the wp_posts table for the image on the guid column.

SELECT ID FROM $wpdb->posts WHERE guid = $imageUrl

As we only need the ID column then we can use the method get_col to make sure we only return this post ID.

function getImageIdByUrl( $url )
{
    global $wpdb;
    $image = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $url ));
        
    if(!empty($image))
    {
        return $image[0];    
    }
        
    return false;
}

The problem you'll find with the above function is that it will not find IDs for images if the URL is for a auto generated thumbnail. Auto generated thumbnail URLs are created by WordPress when you upload an image it will create multiple images with the different sizes of your media items. To find this image in the wp_posts you need to remove the sizes from the URL before searching the guid column on the wp_posts.

function getImageIdByUrl( $url )
{
    global $wpdb;

    // If the URL is auto-generated thumbnail, remove the sizes and get the URL of the original image
    $url = preg_replace( '/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i', '', $url );

    $image = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $url ));

    if(!empty($image))
    {
        return $image[0];
    }

    return false;
}

If we get an image returned from this function we can then use this to add a featured image to the post using the set_post_thumbnail() function.

// Check the array is populated with featured images
if(!empty($featuredImages))
{
    // Get random picture from remaining images
    $randomPicture = array_rand($featuredImages, 1);
    
    // Get an attachment ID of the featured image
    $attachmentId = getImageIdByUrl($featuredImages[$randomPicture]);

    // Check if attachment ID is not false
    if($attachmentId)
    {
        set_post_thumbnail( $post_id, $attachmentId );
    }
}

When you are designing a new website you normally go through a few steps until you have the finished design.

First you will get the requirements for the design from the client, this will lead you to create a wireframe to show the client so you can make sure that it is what they hoped for.

With a wireframe you will get the basic layout of the website but won't really get the look and feel of site for this you need to start the prototyping stage. This is where you will create the site in HTML including dummy text and dummy images.

The easy thing is to include dummy text as you can use lorem ipsum. But it takes more time to create these images and make sure they are the right size for your design. Then if you want to change the sizes of these images you have to go back to your image editor and change the sizes, save the file and add these images back to your prototype page.

Fake images please

The solution is using a placeholder service like fake images please. This service allows you to create fake images at the create sizes using their API, which means you can quickly add these placeholders to your design but just typing in the image URL.

Just like the examples below.

Create An Image 300x300

The simplest form of creating an image is to pass in 1 parameter for the size of the image, this will create an image 300 x 300.

<img src="http://fakeimg.pl/300/"/>

Read more...

When you upload an image to WordPress by default it will be converted to three different sizes.

  • Thumbnail
  • Medium Size
  • Large Size

If you don't want your users to use any of these images sizes on your theme then you might want to stop the user from using these different sizes.

You can remove these from being used by using the WordPress action intermediate_image_sizes_advanced and unset the thumbnail, medium and large sizes, this will mean the only size they have left is the full image size. Read more...

Pinterest-Logo

Pinterest is the newest big thing in the Social media world, this site is an image sharing social network. It allows it's users to pin any image on any website to share with their followers.

There has been a lot of talk about the copyright problems with Pinterest, for example photographers can now have their images shared all over the internet. This can be great for marketing your image but what if there are some images that you don't want to be shared on Pinterest. Read more...

There is a way you can prevent people hotlinking the images on your website just by adding bits of code in your htaccess.

Images Read more...

A way that Browsers try to help speed up rendering the page is by taking static data and cache it. These are things like images, CSS and JavaScript files. As Browsers are going to cache these bits of data you can actually set an expiry so the Browser will know not to cache these anymore.

The Browser will keep serving these until the date you set. Read more...

Since reading the article Just some other awesome CSS3 buttons I become interested about how you can use this effect to get icons on buttons without using any images.

As a web developer I don't really get on with images and if I can avoid using them I will, so when I saw this trick about displaying icons in a button without using any images I wanted to explorer what other icons you can use just by using CSS.

I discovered that there are loads and loads of icons that can be used in your CSS by using Hexadecimal entities.

There are lots of places I found to get the codes for these icons here is a list of places I used to get the most useful icons for this example.

Read more...

seo SEO (Search Engine Optimization) is not a quick process or a guaranteed process and if anyone else tells you anything else they are lying.

No Search Engine Optimization expert can guarantee you number position in Google for your most competitive keywords, but there are things you can do to help your website get to the top of the search engine results.

I'm not saying follow all these tips and you will be top but they can certainly help. Most of these Search Engine Optimization tips are known as on-page Search Engine Optimization (SEO), which means these are things you can change on your existing website. These will be title tags, descriptions, header tags, content and links. Read more...

What?

Using CSS you can put an image as the background image of any images on your web site. Sounds confusing but a image is just a normal HTML DOM element, which means you can add the same CSS attributes to it such as borders and backgrounds.

If you have a website which has large images to load on the page the user will need to wait for them to load leaving a blank space on the screen. Read more...