【问题标题】:One Column to extend to edge of the window and other Column to remain within container一列延伸到窗口边缘,另一列保留在容器内
【发布时间】:2022-06-15 23:56:42
【问题描述】:

我想创建一个两列布局,其中左侧的列占容器的 40%,并与容器保持/对齐,但右侧的列扩展到窗口边缘。我可以使用绝对位置来做到这一点,但我相信有更好的方法来做到这一点。以下是我所做的图像和代码 sn-p。有没有更好的方法来做同样的事情?

div {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: arial;
}

.header {
  padding: 20px 10px;
  background: #EEE;
}

.container {
  max-width: 1000px;
  margin: auto;
  display: flex;
  gap: 0;
  position: relative;
}

.container.wide {
  width: 100%;
  max-width: unset;
}

.relativediv {
  position: relative;
}

.absolute-container {
  width: 100%;
  max-width: 1000px;
  padding: 20px 10px;
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
}

.container.wide :nth-child(1) {
  width: 40%;
}

.container.wide :nth-child(2) {
  width: 60%;
  min-height: 500px;
}

.container.wide :nth-child(2) img {
  height: 100%;
  width: 100%;
  object-fit: cover;
  display: block;
}
<div class="container header">
  Header
</div>

<div class="relativediv">

  <div class="container wide">
    <div></div>
    <div>
      <img src="https://i.picsum.photos/id/0/5616/3744.jpg?hmac=3GAAioiQziMGEtLbfrdbcoenXoWAW-zlyEAMkfEdBzQ" />
    </div>
  </div>

  <div class="absolute-container">
    <div class="content">
      <p>Lorem ipsum dolar sit smit is dummy text. </p>
      <p>Lorem ipsum dolar sit smit is dummy text. </p>
      <p>Lorem ipsum dolar sit smit is dummy text. </p>
      <p>Lorem ipsum dolar sit smit is dummy text. </p>
      <p>Lorem ipsum dolar sit smit is dummy text. </p>
    </div>
  </div>

</div>

【问题讨论】:

  • 为什么要使用 hacky 定位而不是使用 flexboxcss-grid 保持简单?
  • 是的,这很老套,我不喜欢。想用 CSS 网格或 flexbox 来做,但我不知道怎么做,也无法在任何地方找到示例。

标签: html css layout


【解决方案1】:

只需使用 Flexbox 创建 2 列布局。要在左列中垂直居中文本,您也可以使用 flexbox:

.relativediv {
  display: flex;
  flex-direction: row-reverse;
}

.container {
  width: 60%;
}

.container img {
  width: 100%;
}

.absolute-container {
  width: 40%;
  display: flex;
  align-items: center;
}
<div class="container header">
  Header
</div>

<div class="relativediv">

  <div class="container wide">
    <div></div>
    <div>
      <img src="https://i.picsum.photos/id/0/5616/3744.jpg?hmac=3GAAioiQziMGEtLbfrdbcoenXoWAW-zlyEAMkfEdBzQ" />
    </div>
  </div>

  <div class="absolute-container">
    <div class="content">
      <p>Lorem ipsum dolar sit smit is dummy text. </p>
      <p>Lorem ipsum dolar sit smit is dummy text. </p>
      <p>Lorem ipsum dolar sit smit is dummy text. </p>
      <p>Lorem ipsum dolar sit smit is dummy text. </p>
      <p>Lorem ipsum dolar sit smit is dummy text. </p>
    </div>
  </div>

</div>

【讨论】:

    猜你喜欢
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 2013-12-01
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    相关资源
    最近更新 更多