搜索

首页  >  问答  >  正文

不知道如何在移动版和桌面版中定位具有不同顺序的元素

我正在尝试构建一个特定的设计。这是桌面和移动设备上的设计:

.section {
  width: 100%;
  position: relative;
}

.section__inner {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.title {
  color: white;
}

.img {
  width: 100%;
  height: auto;
}

.text-container {
  display: flex;
  flex-direction: column;
  background-color: black;
  color: white;
}

@media only screen and (min-width: 768px) {
  .section__inner {
    width: 175px;
    margin-left: auto;
  }
  .img {
    position: absolute;
    z-index: -1;
    width: 60%;
  }
}
<div class="section">
  <div class="section__inner">
    <h1 class="title">Title</h1>
    <img class="img" src="https://source.unsplash.com/random/" alt="random" />
    <div class="text-container">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur cursus ornare risus. Ut sed gravida magna. Mauris in elit imperdiet, porta turpis a, mollis lorem. Nulla consectetur gravida urna, at condimentum dolor.</p>
      <p>Suspendisse potenti. Cras malesuada lacus sed malesuada efficitur. Maecenas eros leo, sollicitudin convallis nunc nec, maximus blandit nisi. Cras eleifend nisi id risus vestibulum aliquet. Donec maximus justo at nulla blandit, vel dictum nisi volutpat.
        Morbi placerat augue vel libero feugiat, eu venenatis libero aliquet.
      </p>
    </div>
    <button>Go to the link</button>
  </div>
</div>

这是我的代码笔,其中包含我迄今为止开发的内容。我不明白如何定位这些元素以及采取什么方法。

P粉469090753P粉469090753278 天前371

全部回复(1)我来回复

  • P粉322918729

    P粉3229187292024-03-23 00:20:24

    首先,您需要为容器元素设置正确的最大宽度和宽度,并允许其在屏幕上居中(根据您的桌面设计)

    其次,将 .text-container div 放置在左侧,使其位于图像上方,并且由于它已经位于正确的层次结构中,因此无需设置 z-index 它将堆叠在图像的顶部

    最后,将按钮移动到 .text-container 中,以便它可以与文本一起定位

    这是 CSS 的更新部分:

    @media only screen and (min-width: 768px) {
      .section {
        /* Ensure that enough space is available before 1200px, you can tweak this according to your design */
        width: 90%;
    
        /* So the 90% would only apply below this threshold, you can adjust the value as well if needed */
        max-width: 1200px;
    
        /* Center this element */
        margin: auto;
      }
    
      .text-container {
        position: absolute;
        top: 20%;
        left: 50%;
      }
    
      .img {
        width: 60%;
      }
    }

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur cursus ornare risus. Ut sed gravida magna. Mauris in elit imperdiet, porta turpis a, mollis lorem. Nulla consectetur gravida urna, at condimentum dolor.

    Suspendisse potenti. Cras malesuada lacus sed malesuada efficitur. Maecenas eros leo, sollicitudin convallis nunc nec, maximus blandit nisi. Cras eleifend nisi id risus vestibulum aliquet. Donec maximus justo at nulla blandit, vel dictum nisi volutpat. Morbi placerat augue vel libero feugiat, eu venenatis libero aliquet.

    请注意,调整图像大小时,应保持与参考设计相同的纵横比。

    回复
    0
  • 取消回复