【问题标题】:One div on the left side and two divs on the right side [duplicate]左侧一个 div,右侧两个 div [重复]
【发布时间】:2021-09-03 12:01:13
【问题描述】:

我有一个小问题。我正在尝试使用 HTML 和 CSS 编写这样的布局:

Here's the picture of what i want

我看了这个问题: Flexbox 3 divs, two columns, one with two rows 。唯一的问题是你不能给 div 一个边距而不破坏布局。

如果左图较高,则右图应使用剩余空间。 (只有几个盒子我尝试先正确放置。我想私下做造型,所以不要怀疑。)

这是我到目前为止尝试过的代码(按整页。在这个小窗口中,您只能看到移动版本):

* {
  margin: 0;
  padding: 0;
}

#showroom {
  height: 500px;
  width: 100%;
  background: red; /* To see showroom Background */
  padding: 1em;
  display: flex;
}

#boxOne {
  height: 100%;
  width: 50%;
  background: grey;
  margin: 10px;
  float: left;
}

#showroom #boxTwo {
  width: 50%;
  height: 50%;
  background: grey;
  margin: 10px;
}

#showroom #boxThree {
  width: 50%;
  height: 50%;
  background: grey;
  margin: 10px;
}

@media only screen and (max-width: 750px) {
  #showroom {
    display: flex;
    align-items: center;
    flex-direction: column;
  }
  
  #showroom #boxOne, #showroom #boxTwo, #showroom #boxThree {
    height: 33.3%;
    width: 100%;
  }
}
<div id="showroom">
  <div id="boxOne"></div>
  <div id="boxTwo"></div>
  <div id="boxThree"></div>
</div>

【问题讨论】:

  • 这是 HTML 的结尾还是你可以改变一下?
  • @AristeidisKaravas 你会添加什么?

标签: html css


【解决方案1】:

更新

要使#boxOne 更宽,我们应该查看网格父级,我们说的是3 列宽,每列代表120px

现在让我们看一下#boxOne,然后捕获/修复我引入的错误。

#boxOne {
  grid-column: 1; /* Oops—this is wrong */
  grid-row: 1 / 3;
}

我们将网格声明为 3 列,但 #boxOne 仅跨越一列。其他框也跨越一列。这是我们的网格现在的样子。

您可以看到我们甚至没有使用第三列。让我们调整#boxOne 使其跨度是其他框的两倍。一个非常重要的细节是从第一条垂直线开始计数。想想这样的列:

现在应该清楚我们需要做什么了。

#boxOne {
  grid-column: 1 / 3;
  …
}

我们将放置在#boxOne 停止的跨度位置。

#boxTwo {
  grid-column: 3;
  …
}

#boxThree {
  grid-column: 3;
  …
}

现在事情正朝着我们想要的方向发展。


我会使用 CSS Grid 来解决这个问题。在您的示例中,图像将隐式占用必要的空间,并且您不需要在声明grid-template-columns 的行中使用px 值。在您的情况下,您可以将 120px 替换为 1fr,这是 CSS Grid 使用的小数单位。

使用 CSS Grid 的另一个优点是您可以避免大量额外的 widthheight 设置,以及为项目之间的间隙使用边距。

#showroom {
  display: grid;
  grid-template-columns: repeat(3, 120px);
  gap: 1rem;
}

#boxOne {
  grid-column: 1 / 3;
  grid-row: 1 / 3;
}

#boxTwo {
  grid-column: 3;
  grid-row: 1 / 2;
}

#boxThree {
  grid-column: 3;
  grid-row: 2 / 3;
}

#showroom > * {
  background-color: #444;
  padding: 20px;
  border-radius: 5px;
}
<div id="showroom">
  <div id="boxOne"></div>
  <div id="boxTwo"></div>
  <div id="boxThree"></div>
</div>

【讨论】:

  • 非常感谢,这正是我想要的。但是有没有办法让 ONLY boxOne 变宽?如果是这样,这将如何与网格系统一起使用?抱歉,我是Grid noob
  • @JustChillinInDaHood 我已经为您更新了答案,并包含了一些关于如何考虑网格的必要解释。
  • 我很抱歉,但你知道如何让它响应吗?对于 750 像素的页面宽度,所有框的宽度都应为 100%,并且所有框的高度都应相同,因此约为 100 像素。很抱歉打扰您@media screen and (max-width: 750px){}
  • @JustChillinInDaHood 我会利用你目前所拥有的并创建一个新问题。
  • 谢谢,这是个好主意
猜你喜欢
  • 2018-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-08
  • 1970-01-01
  • 1970-01-01
  • 2011-12-28
相关资源
最近更新 更多