Randomblue
Randomblue

Reputation: 116283

Have divs "tight fit"

This is the structure of my HTML:

<div> <span>Some text</span> <br/> <span>Not much text</span> </div>
<div> <span>Some text</span> <br/> <span>Not much text</span> </div>
<div> <span>Some text</span> <br/> <span>Not much text</span> </div>

I have three divs all of which contain 2 spans with not much text. I want all three divs to appear on the same line. At the moment, each div takes up the whole width of a new line.

I don't want to hardcode a width. I would much prefer if the divs behaved like spans in the sense the they have a "tight fit" for their content (no whitespace).

Upvotes: 5

Views: 7466

Answers (4)

Greg
Greg

Reputation: 21909

DIVs, by default, behave as "block level" elements. Block-level elements typically contain inline elements and other block-level elements. When rendered visually, block-level elements usually begin on a new line.

div {
    display: inline-block;
}

As there are plenty of tags to choose from, a rule of thumb that I go by is to say if you require an element that behaves like another element, there is probably a more appropriate choice of element to be made.

Upvotes: 1

No Results Found
No Results Found

Reputation: 102745

I don't know why everyone is saying float:left or display:inline-block; when you said you wanted the div to behave like a span. The correct way to do that is this:

div {
    display: inline;
}

Ignore anyone saying this:

"If you want it to look like a span, use a span tag"

It's not true and that's what CSS is for - describing what content should look like, HTML is for describing what the content is.

I'm sure you have your reasons for choice of tags, and there are probably better ones to choose but it's impossible to say without any actual context. However <div> and <span> have no actual semantic meaning.

Upvotes: 6

pinaldesai
pinaldesai

Reputation: 1815

I think this is what you want,

    <div style="float:left;padding:2px;"> <span>Some text</span> <br/> <span>Not much text</span> </div>
    <div style="float:left;padding:2px;"> <span>Some text more text</span> <br/> <span>Not much text</span> </div>
    <div style="float:left;padding:2px;"> <span>Some text more more and more text</span> <br/> <span>Not much text</span> </div>

Ignore padding, It's just to have better view.

Upvotes: 0

Hux
Hux

Reputation: 3122

The easiest way would be to apply float left to the div so that they sit inline. Or, you could apply display:inline-block to the div, but that would only work in IE8+.

But I have to ask the question, why do you need the div tag initially? it seems like you are creating more work for yourself here.

I would prefer to start with an inline element such as a span, then apply display:inline-block for padding, margin's if needed.

Upvotes: 4

Related Questions