如何避免標籤換行?
使用標籤時,瀏覽器通常會將容器內的專案放在下一行。例如,程式設計師需要將標題放在一行中以建立導航元件。我們可以使用內聯、內聯塊、彈性盒屬性等來避免標籤換行。
本文將解釋如何透過使用內聯屬性、彈性盒屬性等方法來避免標籤換行。
使用內聯屬性
避免標籤換行的一種常用方法是使用內聯屬性。此屬性強制新行保持與前一行相同。
示例
<!DOCTYPE html> <html lang="en"> <style> .first-container{ display: inline; padding:2px; padding:10px; border: 2px solid orange; } .second-container{ display: inline; padding: 10px; border: 2px solid purple; } body{ padding:2vw; } </style> <body> <div class="first-container"> This is the first paragraph. </div> <div class="second-container"> This is the second paragraph. </div> </body> </html>
解釋
HTML程式碼建立了一個簡單的網頁,其中包含兩個容器:“first-container”和“second-container”。body元素的填充為視口寬度的2%。
“first-container”的display值為“inline”,帶有橙色邊框和2畫素和10畫素的填充。它顯示文字“This is the first paragraph.”。“second container”的display值為“inline”,帶有紫色邊框和10畫素的填充。它顯示文字“This is the second paragraph.”。容器並排顯示,由body填充隔開。
使用內聯塊屬性
這與之前的方法類似,但並不相同。
使用內聯和內聯塊的區別如下:
“inline”元素與文字內聯放置,並且只佔用必要的寬度。它們不會建立新的塊級格式化上下文,也不會在新行開始,因此不能設定寬度、高度或邊距。“inline”元素的示例包括“span”標籤和“a”標籤。
“inline-block”元素類似於“inline”元素,但可以設定寬度、高度和邊距。它們還會建立一個新的塊級格式化上下文,這意味著可以設定填充、邊框和背景顏色。但是,它們仍然會與文字內聯放置,並且不會在新行開始。“inline-block”元素的示例包括具有已定義尺寸的影像和按鈕。
示例
<!DOCTYPE html> <html lang="en"> <style> .first-container{ display: inline-block; padding:3px; padding:15px; border: 3px solid rgb(0, 47, 255); } .second-container{ display: inline-block; padding: 15px; border: 3px solid rgb(92, 24, 42); } body{ padding:2vw; } </style> <body> <div class="first-container"> This is the first paragraph. </div> <div class="second-container"> This is the second paragraph. </div> </body> </html>
使用彈性盒
一種非常流行的方法是使用彈性盒及其相關屬性與標籤一起使用,以避免換行。
示例
<!DOCTYPE html> <html lang="en"> <style> .first-container { padding: 3px; padding: 15px; border: 3px solid rgb(13, 108, 75); } .second-container { padding: 15px; border: 3px solid rgb(214, 59, 100); } .third-container { padding: 15px; border: 3px solid rgb(59, 59, 214); } body { padding: 2vw; } .container { display: flex; flex-direction: row; } </style> <body> <div class="container"> <div class="first-container">This is the first element.</div> <div class="second-container">This is the second element.</div> <div class="third-container">This is the third element.</div> </div> </body> </html>
解釋
此HTML程式碼建立了一個簡單的網頁,其中包含三個容器,每個容器都有一個不同的類。body元素的填充設定為視口寬度的2%。first-container、second-container和third-container元素具有填充和不同顏色的邊框。
這些容器放置在一個具有類“container”的父容器內,該容器具有`display: flex`和`flex-direction: row`樣式。這將容器元素設定為彈性容器,並將子元素按行內聯顯示,並帶有各自的樣式和填充。
結論
本文教我們如何使用標籤避免換行。我們可以使用內聯、內聯塊、彈性盒屬性等來避免換行。程式設計師同樣使用所有這些方法。