【问题标题】:Making an image half the page width inside of a smaller container在较小的容器内制作一半页面宽度的图像
【发布时间】:2016-12-01 11:09:02
【问题描述】:

我正在尝试将照片设置为 50vw(页面宽度的一半),始终与屏幕左对齐,仅使用 CSS -- 不重构 HTML。我希望 flexbox 的另一半保持在容器内的中心。

基本上,如果你的屏幕是 1600px 宽,Nick Cage 应该从左侧的 0px 开始并延伸到 800px(中心),然后.hero-text 应该从 800px 开始并在 1400px 结束,因为它保持在1200px 宽度的容器。

我已经注释掉了我认为很关键的一行,但我无法正确计算。无论分辨率如何,我只需要将图像偏移为始终位于屏幕的左边缘。

.container {
  width: 100%;
  border: 1px solid blue;
  height: 500px;
}
.inner {
  width: 1200px;
  height: 100%;
  margin: 0 auto;
  border: 1px solid red;
}
.hero {
  width: 100%;
  height: 100%;
  border: 1px solid green;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  text-align: center;
}
.hero > div {
  width: 50%;
}
.hero-image {
  width: 50vw;
  height: 100%;
  /* margin-left: calc((100vw - 1200px) * -1); */
  background: url('https://www.placecage.com/c/500/400');
  background-repeat: no-repeat;
  background-size: cover;
}
<div class="container">
  <div class="inner">
    <div class="hero">
      <div class="hero-image">
      </div>
      <div class="hero-text">Here is Nick Cage, everybody!
      </div>
    </div>
  </div>
</div>

https://jsfiddle.net/cqu6xf90/1/

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    无需使用任何计算。

    使用相对和绝对定位来实现这一点。 请参阅此处以获取更多信息。 https://css-tricks.com/absolute-positioning-inside-relative-positioning/

    您可以将任何子元素“绝对”定位为相对父元素。

    在这种情况下,将容器元素设置为具有position: relative; & 将英雄图像设置为 position: absolute; left: 0; 实际上会将其设置在元素的左侧。

    完整的CSS

    .container {
      width: 100%;
      border: 1px solid blue;
      height: 500px;
    /*  Relative Parent  */
      position: relative;
    }
    
    .inner {
      width: 1200px;
      height: 100%;
      margin: 0 auto;
      border: 1px solid red;
    }
    
    .hero {
      width: 100%;
      height: 100%;
      border: 1px solid green;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      text-align: center;
    }
    .hero > div {
      width: 50%;
    }
    .hero-text {
    /*  Margin to place the text div  */
      margin-left: 50%;
    }
    .hero-image {
    /*  Positions the hero image where you want it   */
      position: absolute;
      left: 0;
      width: 50vw;
      height: 100%;
      /* margin-left: calc((100vw - 1200px) * -1); */
      background: url('https://www.placecage.com/c/500/400');
      background-repeat: no-repeat;
      background-size: cover;
    }
    

    查看此代码笔 http://codepen.io/anon/pen/NbwVmy 以查看它的工作原理。

    希望这就是您想要的! (当然不会弄乱标记)

    【讨论】:

      猜你喜欢
      • 2017-08-29
      • 2018-02-14
      • 1970-01-01
      • 1970-01-01
      • 2019-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-03
      相关资源
      最近更新 更多