Set background as wide as the text and align left after line break

68 views Asked by At

This is a chat box example where I want the span.p elements to be on the right side, I also want the background to be as wide as the text:

<div id="msgWindow" class="block">
<div id="messages">
<p class="sysmsg">You're now connected with a random chat partner...</p>
<p class="sysmsg">Say Hello!</p>
<p class="msg-item"><span class="you">hi</span></p>
<p class="msg-item"><span class="you">this is a long woooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooord</span></p>
</div>
</div>

I am trying with this CSS code:

#msgWindow{
    position: relative;
}
#messages{
    height: 350px;
    padding: 10px;
    overflow: auto;
    word-wrap: break-word;
}
#messages p{
    padding: 5px 0;
    }
.msg-item{
}
.you, .stranger{
    padding: 4px;
    color: #FFF4F4;
    font-weight: bold;
    border-radius: 0.5em;
    -moz-border-radius: 0.5em;
    -webkit-border-radius: 0.5em;
    margin-right: 5px;
}
span.you{    
    display: inherit;
    margin-left: 60%;
    width: 100px;
    background-color: #555;
    text-align: right;
    word-wrap: break-word;
    direction: rtl;
}

but the text isn't left aligned after line break and also the background isn't set for text only.

This is a demo of what I am talking about: https://jsfiddle.net/dhb0r3k7/

Any help would be appreciated!

2

There are 2 answers

0
zebraman On

If I'm reading your question right you are looking to have variable sized, right floated text boxes with left-aligned text. You could try something like this:

.msg-item{
  clear: both; // <-- one msg item per row
}
span.you{    
    float:right; // <-- right floated text box
    max-width: 40%; // <-- up to 40% of parent div
    text-align: left; // <-- text is left-aligned
    margin-left: 60%;
    background-color: #555;
    word-wrap: break-word;
    direction: rtl;
}
0
Nerrickk On

Your question isn't entirely clear on what you're asking, but I think this is what you're looking for:

On your msgWindow div, put display: inline-block. And in your span.you class, change textAlign: right to textAlign: left