Remove Width and Height from WordPress Images

When you upload an image on WordPress and add it to your post or page, it automatically adds dimensions to the img tag. This is a huge issue for responsive web design, because inline CSS overrides any external CSS. Which means that img { max-width: 100%; } will not work at all!

Technically speaking, you can use !important in your CSS rule, but I don’t think you should, because it’s considered bad practice. What you actually need to do is remove the width and height attributes from your img tag. A very simple solution is to add a couple of WordPress filters to your functions.php file in your theme folder.

// REMOVE IMAGE WIDTH & HEIGHT ATTRIBUTES
function remove_dimension_attributes( $html ) {
    $html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
    return $html;
}
add_filter( 'post_thumbnail_html', 'remove_dimension_attributes', 10 );
add_filter( 'image_send_to_editor', 'remove_dimension_attributes', 10 );

Post a Comment

To post code, use the code tag with a class language-*
Examples: code class="language-markup"code class="language-css"