html - Bootstrap 列的中心背景图像

标签 html css twitter-bootstrap background-attachment

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

这是我的代码:

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/

最佳答案

背景图像是固定的(background-attachment: fixed;)所以它在视口(viewport)而不是列的中心。

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

background-position: 58.33325% center;

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

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

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

关于html - Bootstrap 列的中心背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42734089/

相关文章:

css - 如何在水平列表中修复这个垂直居中的元素符号?

javascript - <i> 标签在按钮元素内变为可点击

html - Clearfix 不适用于固定宽度的列

html - 在 slim 中使用粗体或斜体等标签?

html - 如何将图像保存到硬盘而不在新窗口中打开

html - 当我们在一个 html 页面中有 2 个表单时如何更改按钮的位置

jquery - Bootstrap 4 - Nav - 隐藏额外的菜单项

javascript - 如何使单击的选项卡及其内容处于事件状态,而其他选项卡处于非事件状态?

Javascript 图像 onclick

jquery - jquery mobile gridview的onclick事件