Search code examples
javascripthtmlcsstextwidth

HTML/CSS - All text elements are 23 pixels wide no matter the text content


I have some text elements (h1) and they all for some reason are the same width, even while having different text in them.

HTML:

<h1 class="main-text" id="one">text</h1>
<h1 class="main-text" id="two">texttextext</h1>
<h1 class="main-text" id="three">texttextexttexttextext</h1>

CSS:

.main-text {
  position: relative;
  left: 50%;
  transform: translate(-50%, 0);
  text-align: center;
  color: #848484;
  font-family: "Roboto";
  font-size: 40px;
}

For some reason, when I run the following JS code:

console.log(document.getElementById("one").offsetWidth)
console.log(document.getElementById("two").offsetWidth)
console.log(document.getElementById("three").offsetWidth)

All of them log as 23. My screen width is 1920px if that helps. Is there something in my CSS that might be causing this?


Solution

  • h is a block level element , so it will try to occupy the full width of the parent

    Use display:inline-block to set the width according to the content and for line break use <br/>

    console.log(document.getElementById("one").offsetWidth)
    console.log(document.getElementById("two").offsetWidth)
    console.log(document.getElementById("three").offsetWidth)
    .main-text {
      position: relative;
      left: 50%;
      transform: translate(-50%, 0);
      text-align: center;
      color: #848484;
      font-family: "Roboto";
      font-size: 40px;
      display: inline-block;
    }
    <h1 class="main-text" id="one">text</h1>
    <br/>
    <h1 class="main-text" id="two">texttextext</h1>
    <br/>
    <h1 class="main-text" id="three">texttextexttexttextext</h1>