WordPress Caption Width Issue

Wordpress Caption Width Issue

When using an image caption in wordpress, the image and the caption is wrapped within a additional div with a class of wp-caption. By default WordPress increases the width of the div by 10 pixels. If your image is 600 pixels wide, the wp-caption div will be 610 pixels wide. This can cause issues like horizontal scrolling, causing parts of images to be hidden, breaking layout, or not fitting with the rest of the web site’s aesthetics.

Fixing the issue

The width can not be altered with CSS because it’s an inline CSS rule, hardcoded into the PHP behind wordpress.

If you want to change the width of the wp-caption div element…

  1. Navigate to root/wp-includes and open media.php in a text editor.
  2. Find the following piece of code.
    return '<div ' . $id . 'class="wp-caption ' . esc_attr($align) . '" style="width: ' . (10 + (int) $width) . 'px">'
    	. do_shortcode( $content ) . '<p class="wp-caption-text">' . $caption . '</p></div>';
    
  3. If you want a different default width, change 10 to the width you want. The width of the wp-caption div will be the number you choose, added with the width of the image. If you put 0 instead of 10, the width of the wp-caption div and the image will be the same.
  4. If you don’t want to set a default width, delete the following code from the snippet above.
    style="width: ' . (10 + (int) $width) . 'px"
    
  5. Save the changes to media.php and test.

David AnastasiWritten by David Anastasi - A web designer and front-end web developer based in Southampton, UK. David Anastasi on Twitter