【问题标题】:Right aligned Bootstrap container which also aligns with default container右对齐 Bootstrap 容器,它也与默认容器对齐
【发布时间】:2019-06-27 02:27:10
【问题描述】:

我一直在尝试制作一个 Bootstrap 容器,它“溢出”到页面的右侧,但也与标准的 Bootstrap 容器很好地对齐。到目前为止,我已经尝试复制标准容器的代码并更改 max-width 值,但我似乎永远无法使其与标准容器保持一致。这是我目前所拥有的:

  width: 100%;
  padding-left: 15px;
  margin-left: auto;
  margin-top: 3rem;

  @media (min-width: 576px) {
    max-width: 675px;
  }
  
  @media (min-width: 768px) {
    max-width: 900px;
  }
  
  @media (min-width: 992px) {
    max-width: 1200px;
  }
  
  @media (min-width: 1200px) {
    max-width: 1425px;
  }

有人能帮我实现吗?

【问题讨论】:

标签: css twitter-bootstrap bootstrap-4


【解决方案1】:

您可以根据每个断点的 Bootstrap container 宽度计算自定义容器宽度的左边距。为了使其与容器对齐,左边距将是:

margin-left: calc(50vw - (container width/2))

所以 CSS 应该是:

.container-custom {
   padding-left: 15px;
   padding-right: 15px;
}

@media (min-width:576px){
  .container-custom {
    margin-right: 0;
    margin-left: calc(50vw - 270px);
  }
}

@media (min-width:768px){
  .container-custom {
    margin-right: 0;
    margin-left: calc(50vw - 360px);
  }
}

@media (min-width:992px){
  .container-custom {
    margin-right: 0;
    margin-left: calc(50vw - 480px);
  }
}

@media (min-width:1200px){
  .container-custom {
    margin-right: 0;
    margin-left: calc(50vw - 570px);
  }
}

演示:https://www.codeply.com/go/gO5EmIIeDi

【讨论】:

    【解决方案2】:

    这是另一种绝对定位的方法。

    诀窍是自定义相对定位自定义容器的:after,使其左侧位于自定义容器的 100%,右侧位于 -(50vw - 50%)。百分比与相对定位的自定义容器有关。

    如果您使用 Bootstrap SASS 文件制作自定义主题,Zim 的方法非常好,因此您会得到$container-max-widths。我的方法不需要知道容器的宽度,因为它使用百分比进行绝对定位!

    布局

    <div class="container container-custom text-center bg-primary text-white">
        ...
    </div>
    

    风格

    .container-custom {
        position: relative;
    }
    
    .container-custom:after {
        content: '';
        position: absolute;
        left: 100%;
        top: 0;
        bottom: 0;
        right: calc(50% - 50vw);
    }
    
    .container-custom.bg-primary:after {
        background-color: var(--primary);
    }
    

    结果

    演示: https://jsfiddle.net/davidliang2008/gj21tdea/23/

    【讨论】:

    • 是的,如果 OP 没有问题,自定义容器内的内容被限制为容器的宽度,这也可以工作。这也会导致 body 上的水平滚动。
    • @Zim:这就是为什么我要评论并询问 OP 的“溢出”是什么意思,因为从 OP 发布的屏幕截图来看,自定义容器内的内容似乎是居中的,并且仅限于容器的宽度。 :)
    猜你喜欢
    • 2014-06-07
    • 2018-05-23
    • 2022-01-24
    • 2017-04-08
    • 2017-01-18
    • 2021-03-10
    • 1970-01-01
    • 2020-07-28
    • 2021-12-22
    相关资源
    最近更新 更多