My program adding to div a random message generated and pushed by JS to .message:before contains the default background image.png
If the message is long, the image is 50px wide, but if it is shorter, the image is flatter than it should be.
Is there any option to set one image size regardless of message size?
.message {
display: flex;
padding: 5px;
margin: 5px 65px;
height: min-content;
min-width: 10px;
max-width: 400px;
background-color: rgb(98, 117, 180);
border-radius: 20px;
}
.message::before {
content: '';
position: relative;
top: -5px;
right: 60px;
width: 50px !important;
height: 50px;
background-image: url('default-avatar.png');
/* for see result, will generate by js personalised for every user */
background-position: center;
background-repeat: no-repeat;
background-size: 50px 50px;
border-radius: 50%;
z-index: 99;
}
<div class="content">
<div class="chatsContainer">
<div id="chatList">
/* here generated divs with messages */
</div>
</div>
</div>
I deleted max-width from .message and then every image printing good, but I need to set message width shorter than 50% – paddings and margins to set div at left side of .chatList
2
Answers
What I’m seeing is the opposite of what you describe. With a long message your image gets squished, and with a short message it is okay.
The reason for this is because your
::before
is set toposition: relative
. This means it is included in the size calculation for the .message element. If you open your dev tools in the browser and inspect the .message element you should see something like this:One way to resolve this is to use
position: absolute
on the::before
element as it will remove it from the flow of the document. You’ll also need to setposition: relative
on the .message selector because absolutely positioned elements will work with the closest positioned ancestor.After that, just change the
right: 60px
toleft: -60px
in the::before
selector and you should see a result like this:Here’s the css I used for your reference:
For your reference: https://developer.mozilla.org/en-US/docs/Web/CSS/position
Cheers!
You could position the image absolute to the message container. I commeted my changes in the code.