skip to Main Content

I have a <h4> element like this:

<h4 class="hero-title">
    <span>Vessel / tank destruction facility</span>
</h4>

And css like this:

.hero-title {
    background: #000;
    color: #ffffff;
    display: inline-block;
    padding: 20px;
    max-width: 473px;
}

Here is the outcome:

enter image description here

I want to remove the extra spacing on the right side, so that the black background ends at "Vessel / tank", in other words, when line break happens, it should align with the widest word and not take up the entire 473px width.

2

Answers


  1. I couldn’t find any CSS method to do this. I only found this solution using JavaScript.

    Basically, we calculate the bounding box of the text and then determine the width of the parent based on that. (Just make sure that box-sizing is set to border-box.):

    function adjustContainerWidth(element) {
      const textSpan = element.getElementsByTagName('span')[0];
      const boundingRect = textSpan.getBoundingClientRect();
      const horizontalPadding = parseInt(getComputedStyle(element).paddingLeft) + parseInt(getComputedStyle(element).paddingRight);
      element.style.width = (boundingRect.width + horizontalPadding) + 'px';
    }
    
    const elements = Array.from(document.getElementsByClassName('hero-title'));
    elements.forEach((element) => {
      adjustContainerWidth(element);
    });
    .hero-title {
        background: #000;
        color: #ffffff;
        display: inline-block;
        padding: 20px;
        max-width: 473px;
        box-sizing: border-box;  /* for correct width calculation */
        font-size: 60px;
        margin: 5px;
    }
    <h4 class="hero-title">
      <span>Vessel / tank destruction facility</span>
    </h4>
    Login or Signup to reply.
  2. You can use this solution only with CSS.

    .shrink-box {
      max-width: 470px;  
      width: fit-content; 
      padding: 10px;      
      border: 1px solid #000;
      word-wrap: break-word; 
    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Footer at Bottom</title>
        <link rel="stylesheet" href="styles.css">
    </head>
    <body>
    <div class="shrink-box">
      <span>Vessel / tank<br>destruction<br> facility</span>
    </div>
    
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search