2

I want put the background image of my second Bootstrap column in the center of the column. However, right now, it is in the center of the whole view and not at the center of the column.

Here are my codes:

HTML:

<div class="container-fluid cust-main-container">
  <div class="row">
    <div class="col-sm-2">
      <!-- [..] -->
    </div>
    <div class="col-sm-10 bg">
      <!-- [..] -->
    </div>
  </div>
</div>

CSS:

* {
    height: 100%;
} //In my actual code, * is html, body

.cust-main-container,
.cust-main-container > .row {
    height: 100%;
}

.bg{
    background: url('http://placehold.it/150x350');
    background-repeat: no-repeat;
    background-position: center center;
    background-attachment: fixed;
    -webkit-background-size: contain;
    -moz-background-size: contain;
    -o-background-size: contain;
    background-size: contain;
}

.col-sm-2 {
  border: 1px solid blue;
}

.col-sm-10 {
  border: 1px solid green;
}

Here's a jsfiddle: https://jsfiddle.net/1m8ua78z/

Carol Skelly
  • 351,302
  • 90
  • 710
  • 624
shriekyphantom
  • 143
  • 1
  • 4
  • 19

3 Answers3

6

The background image is fixed (background-attachment: fixed;) so it's centering in the viewport instead of the column.

The width of col-*-2 is 16.6666%, and the width col-*-10 is 83.3333%. Therefore, the position of the .bg needs to be: 16.6666%+(83.3333%/2) or...

background-position: 58.33325% center;

Because of responsiveness, you'd only want to apply this before the cols stack vertically on smaller screens..

@media (min-width: 768px) {
    .bg{
        background-position: 58.33325% center;
    }
}

http://www.codeply.com/go/5GG6v3rkZ3

Carol Skelly
  • 351,302
  • 90
  • 710
  • 624
2

You have set background-attachment: fixed; - remove that and set it as background-attachment: scroll;

With fixed "the background is fixed with regard to the viewport", see https://www.w3schools.com/cssref/pr_background-attachment.asp - hence the effect that you got.

A working sample fiddle is here: https://jsfiddle.net/robertjakobson/4ya7pyr5/4/ (I set the background on a div inside the column as a best practice)

-1

Try declaring background-position: 50% 50% or just declare background-position:center