I’m trying to write some basic HTML to display an SMS or Messenger style output.
For some reason I’m having trouble showing the entries on different rows, with sent messages shown on the right and received on the left, and with an expanding height and width for each message.
For example, this version of the HTML is ok except all messages appear on the left. I appreciate that the "from" divs need to be position: absolute
really but that causes the rows to overlay, as you might expect.
body {
background-color: black;
color: white;
}
div.container {
display: inline-block;
position: absolute;
width: 100%;
font-family: Arial;
}
div.row {
display: inline-block;
position: relative;
left: 0;
width: 100%;
height: auto;
padding: 3px;
}
div.from {
display: inline-block;
position: relative;
right: 0;
max-width: 300px;
background-color: blue;
color: white;
border-radius: 15px;
padding: 10px;
}
div.to {
display: inline-block;
position: relative;
left: 0;
max-width: 300px;
background-color: white;
color: black;
border-radius: 15px;
padding: 10px;
}
<div class="container">
<div class="row">
<div class="from">
There once was a man from Caracus, who was larking about like a jackass!
</div>
</div>
<p />
<div class="row">
<div class="to">
Hey!
</div>
</div>
<p />
<div class="row">
<div class="from">
What's up;
</div>
</div>
<p />
<div class="row">
<div class="to">
The sky?? :p
</div>
</div>
<p />
<div class="row">
<div class="from">
Ha ha.
</div>
</div>
<p />
<div class="row">
<div class="to">
Not much. You?
</div>
</div>
<p />
<div class="row">
<div class="from">
Yeah not much.
</div>
</div>
</div>
I’ve tried playing around with display and position types, and also differnt elements (the paragraph tags weren’t there to start with).
I’m trying to avoid using a table.
Is there a change I can make to the styling to get what I want or am I totally barking up the wrong tree here?
3
Answers
Actually just fixed it using
float: right;
andfloat: left;
.I had tried this before but without
clear: both;
which is necessary.A more modern approach would be to use flexbox.
Set
display: flex
on each row (flex-direction: row
). Then if you want the text to be at the right, applyjustify-content: flex-end
; or if you want the text on the left, applyjustify-content: flex-start
.More information on flexbox is here: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
This type of layout scales more gracefully on the modern web, which needs to support many different view ports, devices, etc. And, if you peek at that article, there’s a lot more tweaking and adjustments you can do that you simply don’t have available using an old-school
float
-based layout.Here’s your full example. Note that I replaced the incorrect
<p>
tags;<p>
is for text paragraphs, not for forcing whitespace between blocks elements. (It was replaced with a simplemargin-bottom
.)You can simplify your HTML greatly. There is no real need for additional containers.