The inline-block display property in CSS allows an element to behave like an inline element while retaining the characteristics of a block-level element. This means that elements with display: inline-block can sit next to each other horizontally (like inline elements) but can also have width, height, padding, and margins (like block elements).
Key Characteristics of inline-block:
-
Horizontal Flow: Elements with
inline-blockwill flow horizontally in the same line if there is enough space, similar to inline elements. -
Width and Height: You can set explicit width and height values, allowing for precise control over the size of the element.
-
Padding and Margins: You can apply padding and margins, which will affect the spacing around the element.
-
Alignment: You can align
inline-blockelements vertically using properties likevertical-align.
Example:
Here’s a simple example demonstrating inline-block:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Inline-Block Example</title>
<style>
.inline-block-element {
display: inline-block;
background-color: lightsalmon;
padding: 10px;
margin: 10px;
border: 2px solid red;
width: 150px;
height: 100px;
}
</style>
</head>
<body>
<div class="inline-block-element">Element 1</div>
<div class="inline-block-element">Element 2</div>
<div class="inline-block-element">Element 3</div>
</body>
</html>
Common Use Cases:
- Creating horizontal navigation menus.
- Designing image galleries.
- Aligning elements side by side with precise control over their size and spacing.
Using inline-block is a great way to create layouts without relying on floats or flexbox, especially for simpler designs.
