Roland
Roland

Reputation: 1940

Set width of p element with bg-color to automatically ajust to text length?

I have a p element with a defined Background Color that should adapt it's size automatically to the text inside it. I tried Setting the width to Auto, but the p element still spans 100% as visible by the defined Background Color.

how do I get the width to adjust accordingly without Setting the width in % or px everytime?

Code:

#job-xyz.titel {
    background-color: #dceff5;
    font-size:17px;
    color:black;
    text-align: left;
    margin-top:0px;
    padding-left:10px;
    margin-left:45px;
    width:auto;
}

<div class="header2">

<p class="titel"><strong>Linux Softwaree</strong></p>

</div>

Upvotes: 0

Views: 1201

Answers (2)

NoobEditor
NoobEditor

Reputation: 15891

To set width equal to content, use display:inline-block

#job-xyz.titel {
    background-color: #dceff5;
    font-size:17px;
    color:black;
    text-align: left;
    margin-top:0px;
    padding-left:10px;
    margin-left:45px;
    width:auto;
    display:inline-block /*added*/
}

Also, you have assigned the css wrong way around
#job-xyz.titel
should be
.header2 > p.titel

Your code demo and working demo

final working demo with proper css

Upvotes: 2

Roland
Roland

Reputation: 1940

<p> is a block-element and has to be set to inline via the "Display" property in CSS.

corrected code by "NoobEditor"

#job-xyz.titel {
    background-color: #dceff5;
    font-size:17px;
    color:black;
    text-align: left;
    margin-top:0px;
    padding-left:10px;
    margin-left:45px;
    width:auto;
    display:inline-block /*added*/
}

Upvotes: 0

Related Questions