John
John

Reputation: 746

Pad image if less than 100% width?

I have a situation where I am dynamically displaying images inside of a div. Each div is the same width, but the images aren't.

I set the max-width of the images to 100% and text-align of the div to center. This centers images that are smaller than the div. However, I'd like some padding between the top of the div and the image if the width of the image is less than 100% of the div.

Is there a way to do this with CSS? Or, do I need to use a little bit of JS to accomplish this?

Thanks.

Quick example - http://jsfiddle.net/EFpgA/2/

Upvotes: 0

Views: 1171

Answers (2)

Sean
Sean

Reputation: 427

John- this can be solved with some handy jquery and javascript.

After reading through your markup, it looks as though the largest width of images being generated is 400px.

To solve your padding issue, let's write a javascript function that tests your image width, and based on the width, executes a function that adds padding.

Here's the code with step-by-step explanations of how it works.

In the head of your document, add jquery. In my example I used the google hosted version.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Now that you've got your document loaded with jquery, write out your javascript function that 1) defines your document object, tests its width and executes a function to add padding based on with returned width.

<script>
  function imgPadding(image){
    var image = document.getElementsByTagName('img'); 
      if(image.width != '400px') { //tests for the default 'max' width
        $(image).css({'padding-top': '10px'}); //adds the padding if the test passes
      }
      else {
        return false; //doesn't add padding if the max-width is met
      }
    }
    $(document).ready(function() {
      imgPadding('img'); //calls the function after the images have been loaded
    });
</script>

Upvotes: 0

Richard
Richard

Reputation: 16762

If you don't mind fixing the height of the divs at 400px this will work:

<!-- HTML -->
<div >
    <img src="//lorempixel.com/400/400"/>
</div>

<div >
    <!--I want padding here-->
    <img src="//lorempixel.com/300/300" />
</div>

/* CSS */
div 
{
    width: 400px;
    text-align: center;
    border-width: 2px;
    border-style: dashed;
    border-color: black;
    height: 400px;
    position: relative;
}

img 
{
    max-width: 100%;
    height: auto;
    position: absolute;
    margin: auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

Upvotes: 2

Related Questions