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;`忽略这些属性不同,该元素使用您设置的宽度和高度属性。
  • 元素可以浮动或定位。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

内联、块和内联块的区别

下表显示了`display: inline`、`display: block`和`display: inline-block`属性的区别。

内联 块级 内联块
元素显示在同一行上。 元素显示在新的一行上。 元素显示在同一行上。
它不占据容器的全部宽度。 它占据容器的全部宽度。 它不占据容器的全部宽度。
默认情况下它没有外边距或内边距。 默认情况下它有外边距和内边距。 默认情况下它有外边距和内边距。

CSS 内联和块级示例

这是一个演示`display: inline`、`display: block`和`display: inline-block`属性的不同行为的示例。

示例

Open Compiler
<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属性用于创建水平导航菜单或列表,其中每个导航项都显示为块级元素,但与其他项目保持内联。

示例

Open Compiler
<!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>
广告