Search code examples
htmlcssvariable-length

Width of the element depending on the width of another element - WITHOUT JavaScript


I need the length of the .divider element to be equal to the length of the text (.topic class) + 2em, so that divider is a bit longer than the text. Is this possible using CSS only (no JS)?

Here's the code (and JSFiddle):

<div class="divider"></div>
<div class="topic">
<div class="topic_symbols">@</div>
<div class="topic_text">THIS IS THE SAMPLE TEXT</div>
<div class="topic_symbols">@</div>
</div>
<div class="divider"></div>

.divider {
  border-bottom: 2px solid #fdb239;
  margin-left: 10%;
  margin-right: 10%;
}

.topic {
  display: flex;
  font-family: Tahoma, Geneva, sans-serif;
  justify-content: center;
  align-items: center;
  font-weight: 700;
  font-size: calc(0.8em + 2.3vw);
}

.topic_symbols {
  color: #ee290b;
}

.topic_text {
  text-align: center;
  color: #3cae3f;
  margin: 1% 1em 1% 1em;
}

Solution

  • Don't use a div for styling, instead use pseudo-elements of the .topic_text div.

    .topic_text:before,
    .topic_text:after {
      content: "";
      border-bottom: 2px solid #fdb239;
      position: absolute;
      width: calc(100% + 2em); /* adjust as required */
      left: -1em;
    }
    
    .topic_text:before {
      top: -.25em;
      /* adjust as required */
    }
    
    .topic_text:after {
      bottom: -.25em;
    }
    
    .topic {
      display: flex;
      font-family: Tahoma, Geneva, sans-serif;
      justify-content: center;
      align-items: center;
      font-weight: 700;
      font-size: calc(0.8em + 2.3vw);
      margin-top: 1em;
    }
    
    .topic_symbols {
      color: #ee290b;
    }
    
    .topic_text {
      text-align: center;
      color: #3cae3f;
      position: relative;
    }
    <div class="topic">
      <div class="topic_symbols">@</div>
      <div class="topic_text">THIS IS THE SAMPLE TEXT</div>
      <div class="topic_symbols">@</div>
    </div>