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

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

在此<main>元素之外,我还有一个小的SVG箭头-CSS calc()函数是否可以具有此功能,因此它始终位于主元素上区域的中间左手边?

如果我没有最大宽度属性,我可以做left: 10%,但这只能工作到main元素达到最大宽度为止。

下面是完整的代码,我设法获取了它,使其与main元素的左侧对齐,但是我无法获取,因此它位于左侧空白的一半。我认为CSS中可能无法实现。

Codepen:https://codepen.io/emilychews/pen/bGEJjwX

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

注意2:下图说明了我正在尝试做的事情。

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

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>

iCMS 回答:使用CSS calc()函数将元素保留在多余空间的中间

由于箭头的位置绝对正确,因此相对于主要元素放置箭头要复杂得多。相反,您可以使用包装容器和Flexbox(或默认CSS将子元素垂直和水平居中的方式实现相同的效果(如果我正确理解了您要寻找的内容!)。我更喜欢flex)。>

我所做的是将主要元素和箭头包裹在div中,并标有一类容器。这样,我们可以相对于main和svg相对放置,同时仍保持应用程序的流程。

Display flex会自动将子元素排成一行,从而使svg和主要元素彼此相邻。添加align-items和justify-content中心可确保所有内容保持垂直和水平居中。我删除了边距:0自动;不再需要从主要位置和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%中,我们删除宽度以获得空白。然后,我们用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>

本文链接:https://www.f2er.com/1859590.html

大家都在问