Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make multiple spans equal width within a div

Tags:

html

css

Say I have the following:

<div style="border: 1px solid black; width:300px;">
<span style="background: red; width:100px;">one</span>
<span style="background: yellow; width:100px;">two</span>
<span style="background: red; width:100px;">three</span>
</div>

What CSS can I apply to make the spans equally spaced within the div?

like image 613
Steve Walsh Avatar asked Dec 28 '22 12:12

Steve Walsh


1 Answers

I have to strongly disagree with the other answers, suggesting inline-block and float:left as these solutions will give you a floating layout. This may be fine most of the time, I have seen cases where 33.33% + 33.33% + 33.33% > 100%, usually on Android devices. This pushes the last cell onto the next line.

Since you are trying to create a tabular appearance, I would recommend using tabular display styles:

<style>
    #myTable {
        display: table;
        border: 1px solid black;
        width: 300px;
    }

    #myTable > * {
        display: table-cell;
        width: 33.33%;
    }
</style>
<div id="myTable">
    <span style="background: red">one</span>
    <span style="background: yellow">two</span>
    <span style="background: red">three</span>
</div>
like image 101
Brian Nickel Avatar answered Jan 15 '23 00:01

Brian Nickel