user2096890
user2096890

Reputation: 159

Limiting the width of a paragraph element CSS

I would like my ".tag" div to only be as wide as the text inside it. But, for some reason the paragraph element spans the whole width of the parent element. How can I stop this from happening? So that the ".tag" divs are only as wide as the text inside them?

JSFIDDLE: http://jsfiddle.net/X77e7/

My HTML:

<div class="tag">
    <p> Hiking </p>
</div>

My CSS:

.tag {
    margin: 0px 10px 0px 0px;
    padding: 5px 5px 5px 5px;
    height: auto;
    width: auto;
    border: 1px solid #ddd;
    border-radius: 4px 4px 4px 4px;
    background-color: #f4f4f4;
}
.tag p {
    margin: 0px 0px 0px 0px;
    padding: 0px 0px 0px 0px;
    font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
    font-size: 12px;
    color: #444;
}

Upvotes: 3

Views: 11660

Answers (3)

jhunlio
jhunlio

Reputation: 2660

just float your .tag and your problem is solved

.tag {
    float:left;
    margin: 0px 10px 0px 0px;
    padding: 5px 5px 5px 5px;
    height: auto;
    width: auto;
    border: 1px solid #ddd;
    border-radius: 4px 4px 4px 4px;
    background-color: #f4f4f4;
}

demo

Upvotes: 0

TimPetricola
TimPetricola

Reputation: 1491

Both div and p are block elements. So you should consider setting the display at inline.

.tag {
    display: inline;
    margin: 0px 10px 0px 0px;
    padding: 5px 5px 5px 5px;
    height: auto;
    width: auto;
    border: 1px solid #ddd;
    border-radius: 4px 4px 4px 4px;
    background-color: #f4f4f4;
}

.tag p {
    display: inline;
    margin: 0px 0px 0px 0px;
    padding: 0px 0px 0px 0px;
    font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
    font-size: 12px;
    color: #444;
}

http://jsfiddle.net/X77e7/2/

Upvotes: 0

Sowmya
Sowmya

Reputation: 26969

Add display:inline-block

It is stretching now because div is by default block element which occupies the whole space.

.tag {
    margin: 0px 10px 0px 0px;
    padding: 5px 5px 5px 5px;
    height: auto;
    width: auto;
    border: 1px solid #ddd;
    border-radius: 4px 4px 4px 4px;
    background-color: #f4f4f4; display:inline-block
}

DEMO

Upvotes: 4

Related Questions