galilee galilee - 1 month ago 20
CSS Question

Background image fixed to container edge

Is it possible to have a body background image aligned to the edge of a container element?

Using boostrap 3, I want a background to the page that is fixed to a container edge, so when resizing, the background moves with the container (ie, in the example below, the background image centered over the container edge):

body bg example

Is this possible with a background image, or would I have to add a new absolutely positioned layer / or javascript...?

Answer

There are several solutions to your question, and it really depends on if you require dynamic sizing of the background. The example I have shown will animate the container dynamically, so you can see how it works.

Approach No. 1: Offset background position with known value

One is if you know the exact dimensions of the image, then you can simply position it negatively along the x-axis (i.e. moving it to the left) by half the width of the image. This is assuming that you are not dynamically sizing your background image:

* {
  margin: 0;
  padding: 0;
}
div {
  background-color: steelblue;
  background-image: url('http://placehold.it/400x200');
  background-repeat: no-repeat;
  background-position: -200px 0;
  width: 50%;
  margin: 0 auto;
  height: 500px;
  animation-name: pulse;
  animation-duration: 3s;
  animation-iteration-count: infinite;
}
@keyframes pulse {
  0% {
    width: 50%;
  }
  50% {
    width: 100%;
  }
  100% {
    width: 50%;
  }
}
<div>
Background image dimension: 400x200
</div>

Approach No. 2: Use pseudo/dummy element

If your background size is dynamic (i.e. changes with the size of the container), you are better off using an absolutely positioned pseudo-element or a dummy element:

* {
  margin: 0;
  padding: 0;
}
div {
  background-color: steelblue;
  width: 50%;
  margin: 0 auto;
  height: 500px;
  animation-name: pulse;
  animation-duration: 3s;
  animation-iteration-count: infinite;
  position: relative;
  overflow: hidden;
}
div::before {
  background-image: url('http://placehold.it/400x200');
  background-repeat: no-repeat;
  background-size: 100%;
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  left: -50%;
  right: 50%;
}
div > * {
  position: relative;
  }
@keyframes pulse {
  0% {
    width: 50%;
  }
  50% {
    width: 100%;
  }
  100% {
    width: 50%;
  }
}
<div>
  <p>Background image dimension: 400x200</p>
</div>

Comments