Haradzieniec
Haradzieniec

Reputation: 9340

css: wrap text into div so div takes the length of text

Here is a code:

Fiddle

<div id="main" style="border:1px solid red;">
<div id="child" style="background-color:#68c5e7; width:170px; margin:0 auto; font-size:30px; background-image:url(https://www.google.by/logos/2012/javelin-2012-sr.png); background-repeat   : no-repeat;">
<span style="padding-left:116px;">9:58</span>
</div>
</div>

The time counts using javascript so the length of the string could be changed after the page loaded. How to fix the length of the background #68c5e7 so it has a proper length (corresponds to the length of img+text).

Again, you change 9:58 to 10:03, but the length of background color was not changed, it doesn't fit. One more requirement: the image+text (text is not too long, always no more then a length of main div) should be exactly in the middle of the main div.

Upvotes: 1

Views: 882

Answers (2)

j08691
j08691

Reputation: 207901

Make a few changes:

  1. Remove the width from the container div
  2. Add text-align:center to the parent div
  3. Make the container div have a display of inline-block

jsFiddle example

HTML

<div id="main" style="border:1px solid red;text-align:center">
<div id="child" style="background-color:#24a5a5;  font-size:30px; background-image:url(https://www.google.by/logos/2012/javelin-2012-sr.png); background-repeat   : no-repeat;display:inline-block;">
    <span style="padding-left:114px;"> 12345678</span>
</div>
</div>​

Upvotes: 0

Luis
Luis

Reputation: 5914

Just add all the style to the <span> tag and remove the asigned value to the width:

HTML markup:

<div id="main">
    <div id="child">
        <span> 123456</span>
    </div>
</div>​

CSS markup:

#main{
    border:1px solid red;
}

#child {
    text-align: center;
}

span{
    /*width:190px; */
    padding-left:114px;
    background-color:#24a5a5;
    margin:0 auto; 
    font-size:30px; 
    background-image:url(https://www.google.by/logos/2012/javelin-2012-sr.png); 
    background-repeat: no-repeat;
    white-space:nowrap;
    position: relative;
}

Check this DEMO

Upvotes: 1

Related Questions