如何強制<Div>元素的內容保持在同一行?


<div> 或 division 標籤用於在網頁中分組 HTML 元素,允許我們建立具有相似功能的不同部分,可以使用 Id 或 class 屬性輕鬆設定樣式。HTML <div> 是一個塊級元素,預設情況下,它不會顯示任何與其相鄰的其他 HTML 元素。

Div 是 Web 開發中最有用的標籤,因為它允許我們在網頁中分離資料,併為網頁中的特定資料或功能建立特定部分。它成對使用。內容寫在開始(<div>)和結束(</div>)標籤之間。

示例

讓我們來看一個顯示 div 元素中內容換行的示例。

<!DOCTYPE html>
<html>
<head>
<title>Content layout in a div tag</title>
<style>
    div{
        background-color:lightyellow;
    }
</style>
</head>
<body>
    <h3>There is a div element below this line</h3>
    <div>
        By default, the content wraps itself according to the dimensions of the element within which it is contained. Hence, the text does not get clipped, instead it moves to the next line.
    </div>
</body>
</html>

我們可以觀察到,內容會根據 div 標籤的寬度自動換行,在本例中,div 標籤的寬度由瀏覽器寬度決定。

假設我們為 div 元素設定自定義寬度,例如 250 畫素,內容將根據該寬度自動換行。

但是,我們可以更改預設設定,並使用下面討論的某些 CSS 屬性強制<div>標籤的內容水平顯示在同一行。

使用 Overflow 和 Whitespace 屬性

CSS overflow 屬性指定當內容過大而無法容納在容器中並溢位邊緣時會發生什麼。還有一些姐妹屬性 overflow-y 和 overflow-x,這些屬性不太常用。

overflow 屬性有四個選項:visible(預設)、hidden、scroll 和 auto。我們可以將 overflow 屬性設定為“hidden”以防止內容在元素邊界之外呈現。結果,使用者將無法滾動到框的填充邊緣之外讀取內容,因為內容將在那裡被裁剪。

CSS white-space 屬性

CSS white-space 屬性控制如何顯示空白序列。它指定是否應壓縮空白(合併成單個空格)以及是否應在行尾換行。

white-space 屬性使用 5 個不同的關鍵字值設定:normal、pre、nowrap、pre-wrap 和 pre-line。當 CSS white-space 屬性設定為“nowrap”時,任何兩個或多個空白序列都顯示為單個空白。除非明確指定,否則元素的內容不會換行。

CSS float 屬性用於定位。它用於將元素移動到左側右側,以便另一個元素可以環繞它。它最常用於影像和佈局。

示例

在下面的示例中,我們將 overflow 設定為hidden,並使用 whitespace 屬性的nowrap值強制 div 的內容保持在同一行。

<!DOCTYPE html>
<html>
  <head>
    <title>How to Force the Content of the <div> Element to Stay on the Same Line?</title>
    <style>
      div {
          background-color:whitesmoke;
          height:30px;
          width:250px;
          overflow:hidden;
          white-space:nowrap;
      }
    </style>
  </head>
  <body>
    <div>This is an example of text clipping using the CSS overflow and white-space properties.</div>
  </body>
</html>

使用浮動元素

在這個例子中,我們將使用三個具有固定寬度的浮動元素:div、ul 和 li。為了允許子元件在同一行上水平浮動,子包裝器的寬度設定為大於父級。

示例

<!DOCTYPE html>
<html>
  <head>
    <title>How to Force the Content of the <div> Element to Stay on the Same Line?</title>
    <style>
      #parent {
        width: 300px;
        height: 100px;
        overflow-x: auto;
        overflow-y: hidden;
      }
      #childWrapper {
        list-style: none;
        width: 420px;
        height: 100px;
        margin: 0;
        padding: 0;
        overflow: hidden;
      }
      #childWrapper > li {
        float: left;
        width: 140px;
        height: 100px;
        background-color: thistle;
      }
      #childWrapper > li:nth-child(even) {
        background-color: lavenderblush;
      }
    </style>
  </head>
  <body>
    <div id="parent">
      <ul id="childWrapper">
        <li>111111111111111111111111</li>
        <li>222222222222222222222222</li>
        <li>333333333333333333333333</li>
      </ul>
    </div>
  </body>
</html>

更新於:2023年9月11日

2K+ 瀏覽量

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.