0

I have a "message" element which should be resized if text doesn't fit its width with some limits(just like in messengers).

.message  {
    position: relative;
    color:white;
    background:#182533;
    border-radius:10px;
    padding-top: 5px;
    padding-bottom: 5px;
    padding-left: 10px;
    margin-left: 70px;
    margin-bottom: 10px;
    top: 40px;
    left: -10px;
    max-width: 320px;
    min-width: 70px;
    font-family: 'Open Sans', sans-serif;
    font-size: 14px;
    }
      <div class="message">
      </div>
 

Why it still gets max width even if it's empty?

How it looks like: How it looks like

How it should look like: How it should look like

Sfili_81
  • 2,377
  • 8
  • 27
  • 36
Stunner
  • 33
  • 5
  • Does this answer your question? [absolute vs relative position width & height](https://stackoverflow.com/questions/5323177/absolute-vs-relative-position-width-height) – Sfili_81 Jul 31 '20 at 12:17
  • using display:table is better than the below answer (more support) – Temani Afif Jul 31 '20 at 13:09

1 Answers1

1

I was able to solve this using width: fit-content; as shown in the snippet: MDN

.message {
  position: relative;
  color: white;
  background: #182533;
  border-radius: 10px;
  padding-top: 5px;
  padding-bottom: 5px;
  padding-left: 10px;
  margin-left: 70px;
  margin-bottom: 10px;
  top: 40px;
  left: -10px;
  width: fit-content; /*added fit-content here */
  max-width: 320px;
  min-width: 70px;
  font-family: 'Open Sans', sans-serif;
  font-size: 14px;
}
<!DOCTYPE html/>
<html>
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="test.css" />

<body>
  <div class="message">1-2-3-4-5-6-7</div>
  <div class="message">1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-20-21-22-23-24-25</div>
  <div class="message">1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18</div>
  <div class="message">1-2-3-4-5-6-7-8-9-10-11-12-13-14</div>
  </div>
</body>

</html>
Rob Moll
  • 3,345
  • 2
  • 9
  • 15