如何使用 CSS 將影像並排對齊?


要將影像並排對齊,我們可以在 CSS 中使用float屬性。此外,flex 也允許我們對齊影像。讓我們透過示例逐一瞭解它們,首先從使用 float 屬性將影像並排對齊開始。

使用 Float 將影像並排對齊

我們可以使用 CSS 的 float 屬性將影像等元素浮動到包含父元素的左側或右側。其他元素會圍繞浮動內容放置。具有相同 float 屬性值的多個元素都會並排放置。

在這個示例中,影像使用 float 屬性的值 left 放置在左側。由於所有影像都設定了 float: left,因此它們會並排排列:

.imageColumn {
   float: left;
   width: 25%;
   padding: 10px;
}

.imageColumn 是我們要並排對齊的所有影像的 div:

<div class="imageColumn">
   <img src="https://tutorialspoint.tw/images/clipart/flow/flow4.jpg" alt="Leaf" style="width:100%">
</div>

示例

以下是使用 float 將影像並排對齊的程式碼:

<!DOCTYPE html>
<html>
<head>
   <style>
      * {
         box-sizing: border-box;
      }
      .imageColumn {
         float: left;
         width: 25%;
         padding: 10px;
      }

      h1{
         text-align: center;
      }
   </style>
</head>
<body>
   <h1>Images Aligned Side by Side example</h1>
   <div>
      <div class="imageColumn">
         <img src="https://tutorialspoint.tw/images/clipart/flow/flow4.jpg" alt="Leaf" style="width:100%">
      </div>
      <div class="imageColumn">
         <img src="https://tutorialspoint.tw/images/clipart/cartoon/cartoon2.jpg" alt="Cartoon" style="width:100%">
      </div>
      <div class="imageColumn">
         <img src="https://tutorialspoint.tw/images/clipart/animal/animal9.jpg" alt="Animal" style="width:100%">
      </div>
      <div class="imageColumn">
         <img src="https://tutorialspoint.tw/images/clipart/sport/sport11.jpg" alt="Sports" style="width:100%">
      </div>
   </div>
</body>
</html>

使用 Flex 將影像並排對齊

要將影像並排對齊,請在 CSS 中使用display屬性並將其設定為flex。對齊方式使用justify-content屬性和值center設定:

div {
   display: flex;
   justify-content: center;
}

示例

讓我們來看一個使用 flex 將影像並排對齊的示例:

<!DOCTYPE html>
<html>
<head>
   <style>
      div {
         display: flex;
         justify-content: center;
      }
      img {
         margin: 10px 20px;
      }
   </style>
</head>
<body>
   <h1>Align Images</h1>
   <div>
      <img src="https://tutorialspoint.tw/jsf/images/jsf-mini-logo.jpg" />
      <img src="https://tutorialspoint.tw/cprogramming/images/c-mini-logo.jpg" />
      <img src="https://tutorialspoint.tw/cplusplus/images/cpp-mini-logo.jpg" />
   </div>
</body>
</html>

更新於:2023-11-15

5K+ 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.