从容器中分离固定百分比宽度的图像,并将文本对齐到该容器的左侧

时间:2018-04-10 21:43:27

标签: css css-grid

我希望实现的是在保持文本块与max-widht'ed容器的左侧对齐时,使用max-width'ed容器弹出固定百分比宽度的图像。

我想要的=> view screenshot

(我已将容器的最大宽度设置为300px而不是1200px,以便在stackoverflow上更好地查看。) 所以我需要将绿色文本对齐到紫色文本的左边但是灰色图像始终保持视口宽度的40%。

提前致谢!

见pen =>

.c-container {
  display: grid;
  grid-template-columns: 1fr minmax(0, 300px) 1fr; // 300px as max-width of the container instead of 1200px for clear viewing purposes here on stackoverflow
  grid-template-rows: 48px;
}

.c-container__item {
  grid-column: 2;
  background-color: #FF00FF;
}

.c-content-block {
  grid-template-rows: 48px;
  display: grid;
  grid-template-columns: minmax(0px, 1fr) minmax(0px, 1200px) 40%;
}

.c-content-block__item {
  grid-column: 3 / 4;
  background-size: cover;
  background-position: center center;

}

.c-content-block__item--content {
  grid-column: 2 / 3;
  font-weight: bold;
  background-color: #00FF00;
}
<div class="c-container">
  <div class="c-container__item">
    some content inside container
  </div>
</div>

<div class="c-content-block">
  <div class="content-block__item c-content-block__item--content">
    ---> how can I align this text with the purple container?
  </div>
  <div class="c-content-block__item c-content-block__item--image" style="background-image: url('http://placehold.it/1920x1280');">
    this image always needs to be 40% of the viewport width
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

我想我自己找到了解决方案但是在位置的帮助下:绝对;在图像div上,它从网格顶部延伸到底部。

也许有人可以建议有没有CSS-Grid“唯一”的解决方案而不必使用position:absolute;?

.grid {
  display: grid;
  grid-template-columns: minmax(32px, 1fr) minmax(0,1200px) minmax(32px, 1fr);
  background-color: black;
  position: relative;
}
.item--container{
  grid-column: 2 / 4;
  background-color: #FF00FF;
  margin-right: 40vw;
}
.item {
  grid-column: 2 / 4;
  background-color: #1098ad;
  color: #fff;
  justify-self: end;
  width: 40vw;
  background-color: #00FF00;
  position: absolute;
  top: 0;
  bottom: 0;
}

.item--normal{
  grid-column: 2 / 3;
  background-color: #FF00FF;
}
<div class="grid">
  <div class="item--normal">
    test
  </div>
</div>
<div class="grid">
  <div class="item--container">
    test
  </div>
  <div class="item">
    This item "breaks the grid
  </div>
</div>