CSS - 內聯塊元素



CSS 內聯塊元素是**display**屬性的一個值,它允許元素被格式化為塊級盒子,但像內聯盒子一樣排列。內聯塊元素從同一行開始,但根據元素的高度和寬度佔用多行。

顯示內聯與內聯塊與塊級值

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vesti bulum conseq. uat scel eris que elit sit amet consequat. Nullam cursus fermentum velit sed laoreet.

內聯塊元素的特性

以下是一些內聯塊屬性的關鍵特性

  • `display: inline-block`屬性是`display: inline`和`display: block`屬性的組合。
  • 元素將顯示在與其他內聯元素相同的行上。
  • 如果一行空間不足,元素將換行到下一行,類似於段落中的文字。
  • 與`display: inline;`忽略這些屬性不同,該元素使用您設定的寬度和高度屬性。
  • 元素可以浮動或定位。

內聯、塊和內聯塊的區別

下表顯示了`display: inline`、`display: block`和`display: inline-block`屬性的區別。

內聯 塊級 內聯塊
元素顯示在同一行上。 元素顯示在新的一行上。 元素顯示在同一行上。
它不佔據容器的全部寬度。 它佔據容器的全部寬度。 它不佔據容器的全部寬度。
預設情況下它沒有外邊距或內邊距。 預設情況下它有外邊距和內邊距。 預設情況下它有外邊距和內邊距。

CSS 內聯和塊級示例

這是一個演示`display: inline`、`display: block`和`display: inline-block`屬性的不同行為的示例。

示例

<html>

<head>
    <style>
        span{
            background-color: #1f9c3f;
            border: 2px solid #000000;
            color: #ffffff;
            padding: 5px;
            height: 30px;
            text-align: center;
        }
        .inline {
            display: inline;
        }
        .block {
            display: block;
        }
        .inline-block {
            display: inline-block;
        }
    </style>
</head>

<body>
    <h2>Display Inline</h2>
    <div>
        There are many variations of passages of Lorem Ipsum 
        available, <span class="inline">TutorialsPoint
        </span>, by injected humour, or randomized words 
        which don't look even slightly believable.
    </div>

    <h2>Display Block</h2>
    <div>
        There are many variations of passages of Lorem Ipsum 
        available, <span class="block">TutorialsPoint
        </span> ,by injected humour, or randomized words 
        which don't look even slightly believable.
    </div>

    <h2>Display Inline Block</h2>
    <div>
        There are many variations of passages of Lorem Ipsum 
        available, <span class="inline-block">TutorialsPoint
        </span> by injected humour, or randomized words 
        which don't look even slightly believable.
    </div>
</body>

</html>

使用內聯塊元素的導航連結

inline-block屬性用於建立水平導航選單或列表,其中每個導航項都顯示為塊級元素,但與其他專案保持內聯。

示例

<!DOCTYPE html>
<html lang="en">

<head>
    <style>
        .nav-item {
            display: inline-block;
            padding: 10px 20px;
            margin: 5px;
            background-color: #4CAF50;
            color: white;
            text-decoration: none;
            border-radius: 5px;
        }

        .nav-item:hover {
            background-color: #45a049;
        }
    </style>
</head>

<body>
    <nav>
        <a class="nav-item">Home</a>
        <a class="nav-item">About</a>
        <a class="nav-item">Services</a>
        <a class="nav-item">Contact</a>
    </nav>
</body>

</html>
廣告