Home > Enterprise >  Dynamically position text within, right to or left to an element
Dynamically position text within, right to or left to an element

Time:02-10

I am completely new to CSS. I want to display a simple Gantt chart and I am looking for a way to position the text indicating the number of month within, left to or right to the colored gantt bar.

Right now all the text is within in the bar and as the bar gets narrower it increases in height as the text needs to be wrapped.

Screenshot of current situation

In contrast to what the screenshot currently shows, I would want to have the text for Step 1 to be displayed to the right of the bar, the one for step 5 to be displayed to the left. The rest of the text should remain the same as long as the next is not too long to be wrapped over multiple lines, in that case the next should be displayed on that side right next to the bar where there is more space.

<div style="background-color:green;
padding:10px;
margin-top:-10px;
width:10%;
margin-left:%;
border-radius: 10px;
color:white;
text-align:center;
font-weight:bold
">2months
<div/> 

CodePudding user response:

Check out the white-space: nowrap; and overflow: visible; properties. This won't completely solve your problem - it'll probably just stop the bar from getting too small to contain the text, I'm guessing.

See this link from CSS-tricks for some inspiration. You might be able to use the line-height trick to hide the inner text. To then show text outside the block, you could have a hidden div (either to the left or right) on 'stand-by' that gets displayed only when the inside one is hidden.

CodePudding user response:

The easiest way is probably to just use the padding and margin properties to position your colored div blocks, then displace the text either to the left or right like so:

<div style="background-color:green;
            padding:15px;
            margin-top:10px;
            width:10%;
            border-radius: 10px;
            color:black;
            font-weight:bold">
    
    <div style = "padding: 0px 90px;
                  white-space: nowrap;"
    >2 months</div>
</div>

<br />

<div style = "position: absolute;margin-right: 225px;
              white-space: nowrap;
              color:black;
              font-weight:bold"
>7 months</div>

<div style="background-color:red;
            padding:22px;
            margin-top:-10px;
            margin-left:75px;
            width:10%;
            border-radius: 10px;
            color:black;
            font-weight:bold;"
> </div>

However, this will cause issues if your screen doesn't have a fixed size... you can see this by running the code snippet in full screen. If that isn't the case, hard coding the position like this will work, albeit not necessarily the most elegant solution.

Also, your initial code had a typo in <div/> instead of </div>.

  • Related