Multiple Background Images in CSS

Image showing how the HTML and CSS in this blog post render

Nearly every software developer who works with front-end code has probably used the CSS property background-image. What some might not know is that background-image can take many images and set how those images are positioned. This could be particularly useful if you don’t have full control over the HTML that is being generated for whatever reason. You could also have multiple elements and use an nth-of-type selector to achieve the same effect. Here is a quick demo of how you can use the background-image, background-size, and background-position in concert to apply three images to a single div on top of a span of text.


<div class="box">
  <div class="icon"></div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.      


<pre class="lang:css decode:true" title="CSS Snippet for Multiple Background Images">.box {
  margin: 20px;
  border: 1px solid black;
  padding: 20px;
  background-color: #eee;
  min-width: 430px;  /* Set a min-width, so the images don't spill outside of the container */

.icon {
  height: 100px;
  width: 450px;        /* Set a fixed width, so the images don't float off to the left and right */
  margin: 0 auto;      /* Center the images */
  margin-bottom: 20px; /* Push the text away by 20px */
  background-repeat: no-repeat, no-repeat, no-repeat;    
    100px,       /* height and width of 100px */
    auto 100px,  /* height auto and width of 100px */
    100px;       /* height and width of 100px */
  background-position: left, center, right;  /* You can also set an offset here if you need to */

Those will produce the following result:

Image showing how the HTML and CSS in this blog post render

Here’s a quick demo on JSFiddle:


No Comments

A name is required.
An email is required.
Invalid URL

No comments yet