如何在 HTML 和 CSS 中创建宽度和高度相等的两列布局

问题描述 投票:0回答:1

我正在尝试创建一个两列布局,其中左侧是一个充满文本的 div,右侧是一个带有图像的 div。它们应该在容器中居中,并且它们应该具有相等的宽度和高度,其中右侧 div 的宽度和高度将与左侧 div 的宽度和高度相匹配。该线程所附的图像显示了我想要的效果。我尝试了很多事情,我最好的猜测是:

<div class="container">
    <div class="left-div">
        <p>Some filler text that will cause it to have a width and height that the right div needs to meet</p>
        <p>Another line of filler text that will cause it to have a width and height that the right div needs to meet</p>
    </div>

    <div class="right-div">
        <img src="..." />
    </div>
</div>
.container {
    display: flex;
    justify-content: center;
    align-items: stretch;
}

.left-div {
    flex: 1;

    /* not relevant but i will still include it for accurate context */
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.right-div {
    flex: 1;
}

.right-div img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

但它不起作用,因为图像只是拉伸到最大高度,同时保持其纵横比。 我不知道如何用 CSS 创建这种“依赖关系”。如果我理论上可以为行和列方向设置

flex: 1
,我认为这会起作用,但由于我需要格式化 html 才能获得此布局,我将无法将两个 div 作为子元素包含在内两个分区。不过,我认为通过一些 Flexbox 或 CSS 网格魔法应该可以实现。

非常感谢您的帮助!

html css layout flexbox css-grid
1个回答
0
投票

您可以将

position: absolute
设置为右侧的 div,因此它将从流程中删除,并且不会影响容器的大小。然后将
margin-right
设置为左侧 div,为右侧 div 腾出一些空间,并为其设置一些插图:

.container {
  display: flex;
  justify-content: center;
  align-items: stretch;
  position: relative;
}

.left-div {
  flex: 1; margin-right:50%;
  /* not relevant but i will still include it for accurate context */
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.right-div {
  flex: 1;
  position:absolute;
  top:0; right:0; bottom:0; left:50%;
}

.right-div img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="container">
  <div class="left-div">
    <p>Some filler text that will cause it to have a width and height that the right div needs to meet</p>
    <p>Another line of filler text that will cause it to have a width and height that the right div needs to meet</p>
  </div>

  <div class="right-div">
    <img src="https://picsum.photos/id/522/536/354" />
  </div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.