phone number

A creative, friendly web design company based in Chelmsford, Essex

back light

Make CSS Background Image Fit Dimensions of Div

Using in-line styling, you can adjust the size of an image in your HTML code; but it often poses a problem for coders when they require a background image to be resized to fit the constraints of an existing div.

Why would you want to do this, you may ask? Well one example of usage would be when using an image as a send button perhaps or more likely these days – when using responsive design where your div will respond to the size of the user’s browser (desktop, iPhone, Android, Tablet, iPad etc etc).

make background image fit div with css

In the above image on the left you see the div has a background image that is larger than the div. On the right the same div now has the same image fitting it’s dimensions.

To do this is very simple – here’s the code for a send button:

The HTML needs to have a class added to it (imgclass).

Select Code
<div class="submitbutton2">                 
 <input type="submit" value="" name="submit" class="imgclass" />                               

The CSS code style is very simple:

Select Code
.submitbutton2 { text-align: right; margin: 5% 7% 0 3%; }
.submitbutton2 input { width: 50%; margin: 0 0 7% 5%;  border: none; }

.submitbutton2 input:hover { cursor:pointer; }
.submitbutton2 input:active {color: #eb4e24; border: 3px #eee solid; }

.imgclass { background-image: url(images/fit.png); background-color: inherit; height: 90px; 
background-repeat: no-repeat;
background-size: contain; }

The containing submitbutton2 div is styled to act responsively with a controlling width of 50% of it’s own containing div.

The crucial part here is the background-size attribute which is using contain to force the background image to fit the div. The no-repeat you should be familiar with, as it simply stops the image from tiling.

The aspect ratio of the image – along with the size – by adding a set height to the div, but with no width control added as this is already used in the containing div (remember we’re dealing with a send submit button in this example).

This allows you to fine tune the size of the div and the image. Mess around with it, there will be a limit to how large you can go by altering the height before it stops changing because of the controlling 50% width already set.

Incidentally, the background-color: inherit; in this particular example is forcing the browser to remove the standard grey background that is automatically given to an HTML send button.

Share this..
Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInPin on PinterestEmail this to someoneShare on TumblrShare on StumbleUponShare on Reddit

Tags: , , , , , , , ,

Leave a Reply

Please complete the sum so we know you\'re a human... *