Geek Slack

Introduction to CSS
About Lesson



CSS Layout – display: inline-block


CSS Layout – display: inline-block

The inline-block value for the display property allows you to place elements next to each other horizontally while maintaining the ability to set their width, height, padding, and margin. This makes it a powerful tool for creating flexible layouts.

1. Basic Usage of inline-block

Elements with display: inline-block are similar to inline elements but can accept box model properties such as width and height.

Example:

<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>

<style>
.box {
    display: inline-block;
    width: 150px;
    height: 150px;
    background-color: #ddd;
    padding: 20px;
    margin: 10px;
}
</style>
Box 1
Box 2
Box 3

2. Aligning Inline-Block Elements

By default, inline-block elements are aligned to the baseline. You can change the vertical alignment using the vertical-align property.

Example:

<div class="box" style="vertical-align: top;">Top Aligned</div>
<div class="box" style="vertical-align: middle;">Middle Aligned</div>
<div class="box" style="vertical-align: bottom;">Bottom Aligned</div>

<style>
.box {
    display: inline-block;
    width: 150px;
    height: 150px;
    background-color: #ddd;
    padding: 20px;
    margin: 10px;
}
</style>
Top Aligned
Middle Aligned
Bottom Aligned

3. Inline-Block vs. Block and Inline

Unlike block elements, inline-block elements do not force a new line after the element. Unlike inline elements, you can set the width and height of inline-block elements.

Example:

<div class="box" style="display: block;">Block Element</div>
<div class="box" style="display: inline;">Inline Element</div>
<div class="box">Inline-Block Element</div>

<style>
.box {
    width: 150px;
    height: 150px;
    background-color: #ddd;
    padding: 20px;
    margin: 10px;
}
</style>
Block Element
Inline Element
Inline-Block Element

4. Handling Space Between Inline-Block Elements

One common issue with inline-block elements is the space between them, which is due to the whitespace in the HTML code. There are several ways to handle this, such as removing the space in the HTML or using a negative margin.

Example:

<div class="box">Box 1</div><div class="box">Box 2</div><div class="box">Box 3</div>

<style>
.box {
    display: inline-block;
    width: 150px;
    height: 150px;
    background-color: #ddd;
    padding: 20px;
    margin: 10px;
    margin-right: -4px; /* Adjust this value to handle the space */
}
</style>
Box 1
Box 2
Box 3

Conclusion

The display: inline-block property is a versatile tool in CSS for creating layouts that require elements to sit next to each other while still being able to have widths, heights, padding, and margins. By understanding how to use this property effectively, you can create more flexible and responsive web layouts.

Join the conversation