Arnold Arnold - 1 year ago 67
CSS Question

Background repeat prevent image from showing if it can't be fully displayed

When I repeat a background in CSS, I only want to show the image if it can be fully shown.

Do I have to set the width in pixels? Or is there a CSS property that will only show the image if it can be fully shown?

[dotted image not fully shown]

<div align="left" style="padding-left: 30px;">
<div class="rep_div" style="background:url('file.png'); width:93.5%; display:block;height:3px;"></div>

Answer Source

I'm not sure what exactly you're trying to achieve, but at face value you will need some JS that measures your div's dimensions, measures your image's dimensions and does a simple comparison, then if the div is the same size or larger than the image sets the div's background-image to the image's url.

Here's a basic approximation using CSS and jQuery

/* css */
#container{ image background set here... }

/* js */
var $container = $('#container');
var image = new Image();
image.src = 'path/to/image.jpg';
image.onload = function() {
  if (
    $container.outerWidth() >= this.width &&
    $container.outerHeight() >= this.height
  ) $container.css('background-image': 'url('+image.src+')');

If you are trying to fit exactly the number of repeated images than this code can be easily adapted to not depend solely on "equals or greater", but a multiplication of the image's dimensions.

Be sure to note that this code will only run once, the best practice would be to break out what you see in the image.onload to a separate function. Then run that function from within image.onload, as well as from $(window).on('resize', calculate) providing you called that broken out function "calculate()"

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download