How to wrap two spans into one line with CSS

110,239

Solution 1

Here is the working example:

<div style="float:left;">
    <span style="display:inline; color: red;">First Span</span>
    <span style="display:inline; color: blue;">Second Span</span>
</div>

Solution 2

The float will mess things up. Usually with a float to work you need a width with it as well. It can't float them against each other because it doesn't know how much space each span will occupy in relation to the div. Spans are inherently inline elements unless you define them otherwise, so they should just display that way without the float.

Solution 3

<div style="float:left;">
    <span style="display:contents; color: red;">First Span</span>
    <span style="display:contents; color: blue;">Second Span</span>
</div>

'display:contents' Makes the container disappear, making the child elements children of the element the next level up in the DOM which I believe is the right answer.

Another way which works on ie too is this:

<div style="float:left; display:flex;">
    <span style="color: red;">First Span</span>
    <span style="color: blue;">Second Span</span>
</div>

Solution 4

In some cases display:inline does not work, in such case try adding both spans in one parent span like below

<span>
  <span id="span1">Span 1</span>
  <span id="span2">Span 2</span>
</span>
Share:
110,239
SUN Jiangong
Author by

SUN Jiangong

Updated on March 30, 2020

Comments

  • SUN Jiangong
    SUN Jiangong about 4 years

    I want to wrap two spans in one line with CSS.

    Here is my code:

    <div style="width:60px;">
        <span id="span1" style="float:left; display:inline;"></span>
        <span id="span2" style="float:left; display:inline; "></span>
    </div>
    

    But it doesn't work.

    How to do that?

    Edit:

    I want to use the "id", either use div or span, I just want them to be in one line.

    When I just use span without style, the content are not in the same line. The second line will go down.