如何在HTML中將兩個div並排放置?


DIV標籤就是一個分割槽標籤,顧名思義,它用於劃分網頁上的內容。它有助於分離資料,例如文字、影像、導航欄等,我們也可以使用DIV標籤建立特定的區域。

DIV標籤包含開始和結束標籤<DIV> </DIV>,如果要劃分頁面,這兩個標籤都是必須的。

DIV標籤可以使用CSS進行樣式設定或使用JavaScript進行操作,它可以使用class或id屬性輕鬆設定樣式。任何型別的資料都可以放在<div>標籤內。

示例

以下是<DIV>標籤的示例:

<html>
<head>
   <title>Tutorialspoint</title>
   <style type=text/css>
      p {
         background-color:Red;
         font-size: 35px;
         margin: 8px;
      }
      div {
         color: white;
         background-color: Blue;
         margin: 4px;
         font-size: 25px;
      }
   </style>
</head>
<body>
   <p>How to Represent Div Tags in HTML5</p>
   <div>Welcome To TutorialsPoint</div>
   <div>HTML Tutorial</div>
   <div>CSS Tutorial</div>
</body>
</html>

執行以上程式後,將顯示一個帶有標題的網頁,標題文字分別為白色“歡迎來到Tutorialspoint”、“HTML教程”和“CSS教程”。

在HTML中將兩個div標籤並排放置

我們已經知道div標籤用於建立網頁佈局。因此,我們可以根據需要使用DIV標籤將網頁內容的佈局排列成並排或上下排列。

語法

要將內容並排排列,語法如下:

<style type=text/css>
   .leftdivision
   {
      float: left;
   }
   .middledivision
   {
      float: left;
      background-color:gray
   }
   .rightdivision
   {
      float: left;
   }
   div {
      padding : 2%;
      color: black;
      background-color: pink;
      width: 30%;
      border: white;
   }
</style>

在上例語法中,float: left表示佈局必須從網頁的左側開始。

現在讓我們看一些例子來了解更多關於DIV並排的資訊

示例

現在讓我們看一些例子來了解更多關於DIV並排的資訊:

<!DOCTYPE html>
<html>
<head>
   <title>HTML div</title>
</head>
<body>
   <div style="width: 100px; float:left; height:100px; background:gray; margin:10px">
      First DIV
   </div>
   <div style="width: 100px; float:left; height:100px; background:yellow; margin:10px">
      Second DIV
   </div>
</body>
</html>

執行以上程式碼後,我們將看到兩個DIV標籤並排顯示,每個標籤都有不同的背景顏色和指定的文字。

示例

以下是另一個示例,演示如何將DIV標籤並排放置:

<html>
<head>  
   <title>Tutorialspoint</title>
   <style type=text/css>
      .leftdivision
      {
         float: left;
      }
      .rightdivision
      {
         float: left;
         background-color:gray
      }
      
      div {
         padding : 5%;
         color: black;
         background-color: pink;
         width: 30%;
         border: solid black;
      }
   </style>
</head>
<body>
   <div class="leftdivision">
      <h1>HTML5</h1>
      <p>HTML5 is hyper text markup language latest version, By using HTML we can create our own websites. It describes the structure of web pages.</p>
   </div>
   <div class="rightdivision">
      <h1>Cascading Style Sheets</h1>
      <p>CSS full form is Cascading Style Sheets, It helps in how HTML elements has to be displayed on screen, It controls the layouts of multiple web pages.</p>
   </div>
</body>
</html>

執行以上程式碼後,將顯示兩個DIV標籤並排顯示,具有不同的背景顏色和特定的文字,但與前面的示例相比,這些DIV標籤的高度和寬度有所不同。

更新於:2023年9月29日

49K+ 瀏覽量

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告