Search code examples
htmlcss

Why is HTML width changing what I put down


I’m trying to add a box at the bottom middle of my screen that’s centered and each line goes as much as it wants unless it reaches the full screen then it goes to a new line, I should have coded it correctly out for some reason the max-width isn’t working, the text always goes to 710px then goes puts a line break, no matter what I put the max-width as it always put a line break right there, and no the text that goes there doesn’t have line breaking in it so it can’t be that.

.newalertbox {
  position: fixed;
  bottom: 30px;
  right: 50%;
  background-color: rgba(0, 255, 255, 0.8);
  padding: 5px;
  border-radius: 5px;
  z-index: 1001;
  margin: 0 auto;
  box-sizing: border-box;
  font-weight: bold;
  max-width: 100%;
  width: auto;
  overflow: hidden;
  align-items: center;
  text-align: center;
  transform: translate(50%);
  font-size: 12px
}
<div class="newalertbox">
  <span id="newalerttext"> Special Weather Statement has been issued by NWS Binghamton NY at 1:14pm (Wind= 45 MPH Hail=0.75in) </span>
</div>


Solution

  • The default width calculation method for absolute / fixed positioned elements is "shrink-to-fit". You have defined a max-width - but your element isn't even inclined to grow up to that max-width first, it breaks the text before reaching that already.

    Try and see if this works better for you:

    • position the element at left:0; right:0;, and remove the transform: translate(50%);
    • instead width: auto;, set width: fit-content;

    .newalertbox {
      position: fixed;
      bottom: 30px;
      left:0; right:0; 
      background-color: rgba(0, 255, 255, 0.8);
      padding: 5px;
      border-radius: 5px;
      z-index: 1001;
      margin: 0 auto;
      box-sizing: border-box;
      font-weight: bold;
      max-width: 75%;
      width: fit-content;
      overflow: hidden;
      align-items: center;
      text-align: center;
      font-size: 12px
    }
    <div class="newalertbox">
      <span id="newalerttext"> Special Weather Statement has been issued by NWS Binghamton NY at 1:14pm (Wind= 45 MPH Hail=0.75in) </span>
    </div>