user1427661
user1427661

Reputation: 11794

Sizing an Image in CSS

Forgive me if this question has been asked before, but I always pull together random hacks for images and want to know a definitive way to do what I'm seeking. Here's the HTML:

<div class="track-artwork">
      <img src="<?php echo $chart_track->image; ?>" class="background-image">
      <audio>
          <source src="" type="audio/mp4" />
          <source src="" type="audio/aac" />
      </audio>
  </div>
</div>

The image I'm linking to is 111px X 111px. It needs to be smaller to fit into the track-artwork div and be fully displayed. I do not have the ability to edit the asset's size with something like photoshop. I want to make it so the image acts as a "background" of sorts, sized to fit the "track-artwork" div with 5px of margin on either size. Here's the CSS I've toyed with to achieve this:

.track-artwork {
    cursor: pointer;
    display: inline-block;
    height: 100%;
    margin: 0;
    position: relative;
    vertical-align: top;
    width: 20%;
}

.background-image {
  position: absolute;
  z-index: 0;
  width: 100%;
  top: 0;
  left: 0;
}

Unfortunately, this isn't working out. The width seems to be sized properly, but the height isn't working -- it seems to stay 111px no matter what I input. I've tried it with hard pixel values, but it doesn't change. Thoughts?

Upvotes: 0

Views: 89

Answers (2)

Tim S
Tim S

Reputation: 2329

You can do this with the CSS3 background-size property.

PHP

<div class="track-artwork" style="background-image:url(<?php echo $chart_track->image; ?>);">
    <audio>
        <source src="" type="audio/mp4" />
        <source src="" type="audio/aac" />
    </audio>
</div>

CSS

.track-artwork {
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;
}

IE8 Polyfill

If you need to support IE8, there is a Polyfill. You can get it, and information on how to use it at: https://github.com/louisremi/background-size-polyfill

Upvotes: 1

Smeegs
Smeegs

Reputation: 9224

I would set the image to the div background and use either contain or cover as the background-size.

.track-artwork {
    cursor: pointer;
    display: inline-block;
    height: 100%;
    margin: 0;
    position: relative;
    vertical-align: top;
    width: 20%;
    background-size: cover; // or background-size: contain;
}

Cover will fill the entire div with the background image, cutting off part of the image if the ratios aren't the same.

Contain will resize the image to be fully visible within the div. You'll have to set the background-image url to the correct image location using php.

Upvotes: 1

Related Questions