0

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;
}
HexenSage
  • 117
  • 2
  • 10

1 Answers1

1

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>
Paulie_D
  • 107,962
  • 13
  • 142
  • 161
  • Thsank you so much! I'm not good at pseudo-elements yet, but your answer is a good start point to dive deeper into them. – HexenSage Apr 28 '20 at 08:29
  • A small clarification if you don't mind: adjusting `width` in `.topic_text:before, .topic_text:after` (beginning of the code) changes the width of the orange bar in the **right** direction only. Make it 120% and you'll see what i mean. Is it possible that the width of the bar changes **equally** to both sides (i.e. 120% will add 10% to the width on the right side and 10% on the left side)? Thank you! – HexenSage Apr 28 '20 at 13:48
  • The position of the line is based on the `left` value which is half of the extra width (so 2em wide, adjust leftwards by -1em...see? – Paulie_D Apr 28 '20 at 14:09
  • Yep, solved it myself - wanted to write it here, but you were the first. :-) Thank you a LOT! – HexenSage Apr 28 '20 at 14:58