使用 CSS calc() 函数将元素保持在多余 Space 的中间

Keep Element In Middle Of Excess Space With CSS calc() Function

我有一个 <main> HTML 元素占据页面上 <body> 元素的 80%,它的最大宽度值为 max-width: 1220px

在这个 <main> 元素之外,我有一个小的 SVG 箭头 - CSS calc() 函数是否可能有这个,所以它总是在区域的中间在左侧的主要元素之外?

如果我没有最大宽度 属性 我可以只做 left: 10% 但这只会在 main 元素达到最大宽度之前有效。

完整的代码在下面,我设法得到它,所以它与主要元素的左侧对齐,但我无法得到它,所以它在白色的中间 space在左手侧。我认为在 CSS.

中可能无法实现

代码笔:https://codepen.io/emilychews/pen/bGEJjwX

注意 1:查看下面的代码段时,由于最大宽度值,您需要整页查看它。

注释 2:我正在尝试做的事情如下图所示。

main {
  position: relative;
  margin: 0 auto;
  width: 80%;
  padding: 6rem 0;
  background: red;
  height: 100vh;
  max-width: 1220px;
}

.down-arrow {
  position: absolute;
  width: 1rem;
  height: 1rem;
  bottom: 25vh;

  /* THIS IS THE BIT I NEED HELP WITH */
  left: calc((100% - 1220px) / 2);
}
<main>
  <div class="row"></div>
</main>
<svg class="down-arrow" aria-hidden="true" viewBox="0 0 410.95 355.89">
  <polygon fill="#000" points="205.47 354.89 410.08 0.5 0.87 0.5 205.47 354.89" /></svg>

因为箭头是绝对定位的,所以相对于主元素的定位要复杂得多。相反,您可以使用包装容器和 Flexbox(或默认 CSS 将子元素垂直和水平居中,我更喜欢 flex ).

我所做的是将主要元素和箭头包裹在 div 中,并用 class 容器标记。这样,我们可以在保持应用程序流程的同时,相对于彼此定位 main 和 svg。

Display flex 会自动对齐一行中的子元素,这会将 svg 和主要元素放在一起。添加 align-items 和 justify-content center 确保一切都保持垂直和水平居中。我删除了 margin: 0 auto;来自 main 和来自 svg 的绝对定位,因为它不再需要。

笔有改动,或见下文:https://codepen.io/xenvi/pen/OJMGweV

body {
  margin: 0;
  height: 100vh;
}
  
 .container {
   display: flex;
 }

main {
  position: relative;
  width: 80%;
  padding: 6rem 0;
  background: red;
  height: 100vh;
  max-width: 1220px;
}

.down-arrow {
  width: 1rem;
  height: 1rem;
  bottom: 25vh;
}

.arrow-container, .end-container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-grow: 1;
}
<div class="container">
  <div class="arrow-container">
    <svg class="down-arrow" aria-hidden="true" viewBox="0 0 410.95 355.89">
    <polygon fill="#000" points="205.47 354.89 410.08 0.5 0.87 0.5 205.47 354.89" /></svg>  
  </div>
  <main>
    <div class="row"></div>
  </main>
  <div class="end-container"></div>
</div>

您需要使用 left: calc((100% - 1220px)/4);。我们从 100% 移除宽度以获得白色 space。然后我们除以 2 只得到左边的部分,我们再次除以 2 得到一半。

您也可以使用 min() 使其也适用于小屏幕:

main {
  position: relative;
  margin: 0 auto;
  width: 80%;
  padding: 6rem 0;
  background: red;
  height: 100vh;
  max-width: 1220px;
}

.down-arrow {
  position: absolute;
  width: 1rem;
  height: 1rem;
  top: 25vh;
  left: calc((100% - min(1220px,80%))/4);
  transform:translate(-50%); /* don't forget this to get a perfect centring */
}
<main>
  <div class="row"></div>
</main>
<svg class="down-arrow" aria-hidden="true" viewBox="0 0 410.95 355.89">
  <polygon fill="#000" points="205.47 354.89 410.08 0.5 0.87 0.5 205.47 354.89" /></svg>