首页 > 解决方案 > CSS网格和内联块设计问题

问题描述

我使用 CSS 网格做了一个博客设计,使用 inline-block 将 DIV 打包在一起。

在我的博客中,我有 2 个高度为 60 的图片 DIVS,我想在高度为 120 的文本 DIV 旁边显示。只有第一张图片显示在文本旁边。

为什么第二张图片显示在文本下方,请提供一些有关如何解决此问题的指示。

.GridCont {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-template-rows: auto auto auto;
  grid-template-areas: "content content content content" "content content content content" "content content content content";
}

.PostContent {
  grid-area: content;
  background: #B8E986;
}

.Content {
  background: #000000;
  width: 35%;
  color: white;
  display: inline-block;
}

.box1 {
  height: 120vh;
}

.PicContent {
  background: blue;
  color: white;
  display: inline-block;
}

.pic1 {
  height: 60vh;
  width: 50%;
}

.pic2 {
  height: 60vh;
  width: 45%;
}

.cTextP {
  padding: 20px;
}
<div class="GridCont">
  <div class="PostContent">
    <div class="PicContent pic1">
      <div class="cTextP">Picture #1</div>
    </div>
    <div class="Content box1">
      <div class="cTextP">Content #1</div>
    </div>
    <div class="PicContent pic2">
      <div class="cTextP">Picture #2</div>
    </div>
  </div>
</div>

代码在这个 JS-fiddle

标签: htmlcsscss-grid

解决方案


为什么第二张图片会显示在第一张图片的正下方?没有理由这样做。

第二张图片在第二行。

第二行在第一行的正下方。

更具体地说,第一行由两个元素占据:图像#1 和内容框。第一行的高度由最高元素定义。在这种情况下,这将是内容框。

因此,因为图像#1 没有延伸到第 1 行的整个高度,所以图像之间会有间隙。

以下是对该问题的更详细说明:

(这是一篇与 flexbox 相关的帖子,但这里的逻辑也适用。)

代替inline-block,使用 Grid 属性让内容框跨越两行:

.PostContent {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 60vh 60vh;
  grid-gap: 1em;
  grid-template-areas: " pic1 box1 " 
                       " pic2 box1 ";
}

.box1 {
  grid-area: box1;
}

.pic1 {
  grid-area: pic1;
}

.pic2 {
  grid-area: pic2;
}

.PostContent { background: #B8E986; }
.PicContent  { background: blue; color: white; }
.Content     { background: #000000; color: white; }
.cTextP      { padding: 20px;}
<div class="GridCont">
  <div class="PostContent">
    <div class="PicContent pic1">
      <div class="cTextP">Picture #1</div>
    </div>
    <div class="Content box1">
      <div class="cTextP">Content #1</div>
    </div>
    <div class="PicContent pic2">
      <div class="cTextP">Picture #2</div>
    </div>
  </div>
</div>

修改后的jsfiddle

另请注意,网格属性仅在父元素和子元素之间起作用。


推荐阅读