如何防止內聯塊級div換行?
在CSS中,`display`屬性用於設定子元素的顯示方式。當我們將`display`屬性設定為`inline-block`值時,它會將所有子元素並排顯示。此外,它還會自動建立響應式設計,如果空間不足,它會自動換行子元素。
有時,我們需要阻止子元素換行以管理網頁的空間。在這種情況下,我們可以使用CSS的`white-space`屬性來避免子元素換行。
語法
使用者可以按照以下語法,使用CSS的`white-space`屬性來防止內聯塊級div換行。
CSS_selector { white-space: nowrap; }
在上面的語法中,CSS_selector是所有設定了`inline-block`顯示方式的子元素的父元素。
讓我們透過下面的示例來了解如何防止內聯塊級元素換行。
示例1
在下面的示例中,我們建立了一個包含類名“container”的父div元素。然後,我們在父容器內添加了三個子元素,每個子元素都包含類名“inline-block-div”。
在CSS中,我們為父容器使用了`white-space: no-wrap` CSS屬性,為所有子元素使用了`display: inline-block`屬性。此外,我們還使用了一些其他的CSS屬性來設定div元素的樣式。
在輸出中,使用者可以嘗試減小瀏覽器視窗的大小,並觀察內聯塊級div元素不會換行到下一行。
<html> <head> <style> .container { white-space: nowrap; } .inline-block-div { display: inline-block; width: 200px; height: 100px; border: 1px solid black; margin: 10px; } </style> </head> <body> <h2> Preventing the <i> inline-block divs </i> from wrapping </h2> <div class = "container"> <div class = "inline-block-div"> Div 1 </div> <div class = "inline-block-div"> Div 2 </div> <div class = "inline-block-div"> Div 3 </div> </div> </body> </html>
示例2
在下面的示例中,我們添加了多個包含不同資料的表格。第一個表格包含學校資料,第二個表格包含空調資料。
我們將兩個表格的display屬性都設定為inline-block,以便將它們並排顯示在網頁上。此外,我們還將`white-space`屬性與`container` div元素一起使用。
在輸出中,我們可以看到兩個表格並排顯示,如果我們減小視窗大小,表格也不會換行到下一行,因為我們阻止了兩個表格元素換行。
<html> <head> <style> .container {white-space: nowrap;} .table {white-space: nowrap; display: inline-block; vertical-align: top; margin: 10px; border: 1px solid black;} th, td {padding: 10px 40px; border: 1px solid black;} </style> </head> <body> <h2> Preventing the <i> inline-block divs </i> from wrapping </h2> <div class = "container"> <table class = "container table"> <tr><th> school Name </th> <th> Total Students </th> </tr> <tr><td> ABC School </td> <td> 100 </td></tr> </table> <table class = "container table"> <tr><th> AC brand </th> <th> color </th><th> Price </th></tr> <tr><td> LG </td> <td> White </td> <td> 10000 </td> </tr> </table> </div> </body> </html>
示例3
在下面的示例中,我們演示瞭如何有條件地防止內聯塊級div元素換行。如果需要在特定條件下防止內聯塊級div元素換行,可以使用JavaScript。
在JavaScript中,我們訪問所有div元素,並使用forEach()方法迭代所有div元素。我們使用style物件的`whitespace`屬性,使用JavaScript來防止所有內聯塊級div換行。
<html> <head> <style> .child {width: 300px; background-color: blue; height: 200px; display: inline-block; margin: 10px; color: white; font-size: 30px;} </style> </head> <body> <h2> Preventing the <i> inline-block divs </i> from wrapping </h2> <div class = "parent"> <div class = "child"> First </div> <div class = "child"> Second </div> <div class = "child"> Third </div> <div class = "child"> Fourth </div> </div> <script> let divs = document.querySelectorAll('div'); let divsArray = Array.from(divs); // add white-space: nowrap to all div divsArray.forEach(div => { div.style.whiteSpace = 'nowrap'; }); </script> </body> </html>
使用者學習瞭如何防止內聯塊級div元素換行。我們使用了`white-space` CSS屬性來防止div元素換行。然而,防止內聯塊級div元素換行並不是一個好習慣,因為它會降低網頁的響應性,但在某些特定情況下,如果我們不想垂直擴充套件div元素,我們可以這樣做。