2

我想将我的第二个 Bootstrap 列的背景图像放在列的中心。但是,现在,它位于整个视图的中心,而不是列的中心。

这是我的代码:

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;
}

这是一个jsfiddle:https ://jsfiddle.net/1m8ua78z/

4

3 回答 3

4

背景图像是固定的( background-attachment: fixed;),因此它在视口而不是列中居中。

的宽度col-*-216.6666%,宽度col-*-1083.3333%。因此,.bg 的位置需要是:16.6666%+(83.3333%/2) ...

background-position: 58.33325% center;

由于响应能力,您只想在 cols 在较小的屏幕上垂直堆叠之前应用它。

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

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

于 2017-03-11T10:49:09.720 回答
2

您已设置background-attachment: fixed;- 将其删除并将其设置为background-attachment: scroll;

固定“背景相对于视口是固定的”,请参阅https://www.w3schools.com/cssref/pr_background-attachment.asp - 因此您得到的效果。

一个工作示例小提琴在这里:https ://jsfiddle.net/robertjakobson/4ya7pyr5/4/ (我将背景设置在列内的div上作为最佳实践)

于 2017-03-11T10:48:42.463 回答
-1

尝试声明 background-position: 50% 50% 或只声明 background-position:center

于 2017-03-11T10:40:15.303 回答