Lance B Lance B - 6 months ago 16
Javascript Question

How do I prevent sliced images in the CSS background from sitting on each other?

I have a background image I have sliced in Photoshop and set in a CSS class called".bd-image". I reference this class in the body element because I want it to be the background image for the whole page. I want each image to be 100% and not repeat. The problem is the images are on top of one another and not spreading out on the page. I changed the width and height from the absolute value to 100%, but no success. I need proper coding to set the images.

Does anyone know how to layer sliced images so they go down the page in the correct position and do not overlap? Or does anyone know of a sliced image background I can reference to get the correct coding?

.bd-image{

background:
url(images/orange-dark_01.jpg) 100% 46px no-repeat,
url(images/orange-dark_02.jpg) 100% 60px no-repeat,
.........
url(images/orange-dark_24.jpg) 100% 46px no-repeat;

}

</style>


</head>

<body class="bd-image" onload="StartTimers();" onmousemove="ResetTimers();">

Answer

When multiple images are added as background to an element, CSS would by default place them all in the same starting point. So, they will overlap one another. The background-position property should be used to set each image at their correct place. The value should be set such that the current image is offset from the previous image in X and/or Y directions.

In your case, since all images have to be 100% in width they can all start at X position = 0, only the Y position needs to be set. The Y position of second image would be height of first image, that of the 3rd image would be height of 1st + 2nd image and so on.

div {
  /* as short-hand property */
  background: url(http://lorempixel.com/400/100/nature/1) 0px 0px / 100% 46px no-repeat, 
              url(http://lorempixel.com/400/100/nature/2) 0px 46px / 100% 60px no-repeat, 
              url(http://lorempixel.com/500/100/nature/3) 0px 106px / 100% 46px no-repeat;
  
  /* or as long-hand properties 
  background-image: url(http://lorempixel.com/100/100/nature/1), url(http://lorempixel.com/100/100/nature/2), url(http://lorempixel.com/100/100/nature/3);
  background-repeat: no-repeat;
  background-size: 100% 46px, 100% 60px, 100% 46px;
  background-position: 0px 0px, 0px 46px, 0px 106px;*/
  
  height: 152px;
  width: 200px;
}

/* just for demo - hover to see responsiveness */

div {
  transition: all 1s;
}
div:hover {
  width: 400px;
}
<div></div>

Comments