Reputation: 2066
I have used both of the display
properties whenever I wanted the width of an element to be the same as its content.
But is one better than the other? I'm referring to accessibility, browser compatibility, responsiveness, etc.
Note: I am asking because I'm planing to use only one of these in my new web site. I just don't know which one is better, if any.
Upvotes: 0
Views: 2583
Reputation: 62881
Ultimately, it depends on the use case:
display: inline-block
will create an inline-block
elementdisplay: table
will create a table
elementHere they are in use:
span.mySpan {
background-color: red;
}
<div>
<span>A span element.</span>
<span class="mySpan" style="display: table;">a <code>display: table</code> element.</span>
<span>Another span element.</span>
</div>
<br/>
<br/>
<div>
<span>A span element.</span>
<span class="mySpan" style="display: inline-block;">a <code>display: inline-block</code> element.</span>
<span>Another span element.</span>
</div>
As can be seen, the results are very different. The table
element positions itself on a new line, and causes the next element to be on a new line as well. The inline-block
element positions itself inline with it's sibling elements.
In many cases, the above differences will be enough to choose one or the other.
If not, let's continue...
There are some cases when display: table
is useful:
However, browsers can produce inconsistent results when not implemented correctly so you should always couple display: table
with the standard table markup (using rows and cells):
.table {
display: table;
}
.table-row {
display: table-row:
}
.table-cell {
display: table-cell;
background-color: #eaeaea;
padding: 10px;
}
<div class="table">
<div class="table-row">
<div class="table-cell">
Content
</div>
<div class="table-cell" style="height: 100px;">
Content
</div>
<div class="table-cell">
Content
</div>
</div>
</div>
This becomes pretty tedious. And with modern CSS we can accomplish the same using display: flex
, with a simpler HTML structure and less CSS:
.flex {
display: flex;
}
.flex-cell {
background-color: #eaeaea;
padding: 10px;
}
<div class="flex">
<div class="flex-cell">
Content
</div>
<div class="flex-cell" style="height: 100px;">
Content
</div>
<div class="flex-cell">
Content
</div>
</div>
Honestly, I can't think of many times I would need to decide between display: inline-block
and display: table
as they produce such different results. However, if I were on the fence I'd follow this decision tree:
<table></table>
elementdisplay: flex
elementdisplay: inline-block
)Upvotes: 2