如何在頁面上居中對齊三個 SVG 檔案?
P粉998100648
P粉998100648 2023-09-07 14:20:58

我有三個獨立的 SVG 文件,當它們彼此層疊時,它們將創建一個圖形。第一個 SVG 檔案是一個紅色三角形,第二個是位於三角形內部的藍色圓圈,第三個是位於三角形底部的紫色矩形(三角形和矩形之間有一點空間)。我的目標是將所有三個 SVG 檔案在頁面中央相互疊加。下面是我的 HTML 和 CSS 程式碼。

*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.graphic{
  height: 100vh;
  width: 100vw;
  background-color: palegreen;
  display: grid;
  place-items: center;
  position: relative;
}
.triangle{
  position: absolute;
}
.circle{
  position: absolute;
  top:0;  
}
.rectangle{
  position:relative;
}
<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Graphic-center</title>
      <link rel="stylesheet" href="style.css">
   </head>
   <body>
      <div class="graphic">
         <div>
            <img src="stackoverflow/SVG/triangle.svg" class="triangle" width="150px"/>
         </div>
         <div>
            <img src="stackoverflow/SVG/circle.svg" class="circle" width="150px"/>
         </div>
         <div>
            <img src="stackoverflow/SVG/rectangle.svg" class="rectangle" width="150px"/>
         </div>
      </div>
   </body>
</html>

正如你在我的 CSS 中看到的,我嘗試使用 —position:absolute;和位置:相對; - 但我仍然無法讓它們在頁面中心正確地相互重疊。請記住,一旦SVG 檔案正確居中,我將使用@keyframes 對它們進行動畫處理,並且我需要單獨對它們進行動畫處理(除非有其他方法),因此每個SVG 檔案的位置無法在頁面上固定(即我需要能夠移動它們)。有人可以幫忙嗎?提前致謝。

P粉998100648
P粉998100648

全部回覆(2)
P粉860897943

要居中對齊並覆蓋三個 SVG 文件,您可以使用 Flexbox 和絕對定位。以下是 HTML 和 CSS 程式碼的更新版本:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  height: 100%;
}

.graphic {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  background-color: palegreen;
  position: relative;
}

.triangle, .circle, .rectangle {
  position: absolute;
}

.circle {
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}

.rectangle {
  bottom: 20px; /* Adjust this value to add space between the triangle and rectangle */
}



    
    
    
    Graphic-center
    

具有「graphic」類別的外部 div 使用 Flexbox 水平和垂直居中對齊 SVG 檔案。這確保它們被放置在頁面的中心。

每個 SVG 檔案的位置都設定為絕對位置,以允許它們相互重疊。

圓形 SVG 檔案在其父 div 內居中,使用 margin: auto 並將所有邊(上、右、下、左)設為 0。這使圓在三角形內水平和垂直居中。

使用 Bottom 屬性將矩形 SVG 檔案定位在底部。您可以調整“bottom”的值來增加或減少三角形和矩形之間的空間。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!