搜尋

首頁  >  問答  >  主體

不知道如何在行動版和桌面版中定位具有不同順序的元素

我正在嘗試建立一個特定的設計。這是桌面和行動裝置上的設計:

.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粉469090753246 天前332

全部回覆(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
  • 取消回覆