I have a simple app that outputs messages when some actions are performed on a page, and it is done through the javascript createElement function, what I want to do is add a special style to only the newest message, so if a newer messages comes up the old newest message would revert to the old style. Is there any way to do this? when I createElement it seems all the divs would have to have the same class, and anything I try just applies the style to all the messages.
So is there anything to use in CSS that allows me to only apply a style to the newest member of a certain class?
here is how I create the new messages
function selfMsg(message) {
const msg = document.createElement('div');
msg.style.cssText = 'display: flex; justify-content: flex-end;background-color:aquamarine';
msg.innerText = message;
display.append(msg);
}
but all this does is style all the divs the same style, and I have no idea how I'm supposed to remove the style if a newer message comes up.
Ideally I'm looking for something in CSS that I can use in my stylesheet file that can target an entire class like how ".classnamehere" works, but only applies the style to the newest member of that class.
The <br> HTML element produces a line break in text (carriage-return).
Answer: Use the CSS display Property You can simply use the CSS display property with the value inline-block to make a <div> not larger than its contents (i.e. only expand to as wide as its contents).
It is an inline-level element and does not break to the next line unless its default behavior is changed. To make these examples easier to use and understand for all types of computer users, we're using the style attribute in the div.
Inline elements behave in much the same way as text does. If you want to prevent them from wrapping, either remove the white space you have used for formatting, or add white-space:nowrap; to the rule for .
Depending on the container your divs are in, you can use CSS last:child (https://developer.mozilla.org/en-US/docs/Web/CSS/:last-child) like this:
So if your container has the class display
, you'd do
.display div:last-child {
display: flex;
justify-content: flex-end;
background-color:aquamarine
}
In case you don't know how to use this outside of javascript, simply wrap the above code in a style
tag and add it to the head
of your html document.
For clarity and possibly-upcoming-changes reasons, i highly suggest giving all of your divs a class on creation and using that instead of just div
in the CSS. It's just easier to maintain that way.
.message-wrapper .message:last-child {
color: red;
}
<div class="message-wrapper">
<div class="message">Message 1</div>
<div class="message">Message 2</div>
<div class="message">Message 3</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With