terra823 terra823 -4 years ago 127
CSS Question

:after tag that expands to fill remaining width of div

I have a a h1 element with an :after tag that needs to dynamically expand to fill the remaining width of the containing div. Basically it needs to have a width of calc(h1_width - 100%), where the h1 width isn't set or hardcoded. Can this be done via SASS or will I need to use a JS option to manipulate the DOM? JSfiddle.

HTML

<div class="text-box__wrap">
<h1>Hello</h1>
</div>


CSS

.text-box__wrap {
width: 100%;
margin-top: 2em auto 0;
padding: 0 20px;
}

.text-box__wrap h1 {
margin-bottom: 4%;
letter-spacing: 1.5px;
text-transform: uppercase;
font-size: 12px;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
&:after {
display: inline-block;
/* Needs to be dynamic based on difference of h1 width and remaining div width */
width: 50px;
height: 1px;
margin-left: 10px;
content: "";
vertical-align: 30%;
background-color: black;
}
}

Answer Source

You can use display:flex on the h1 to make the :after take the remaining space:

.text-box__wrap {
  width: 100%;
  margin-top: 2em auto 0;
  padding: 0 20px;
  box-sizing: border-box;
}

.text-box__wrap h1 {
  letter-spacing: 1.5px;
  text-transform: uppercase;
  font-size: 12px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  display: flex;
  align-items: center;
}

.text-box__wrap h1:after {
  display: inline-block;
  height: 1px;
  flex: 1 1 auto;
  margin-left: 10px;
  content: "";
  background-color: black;
}
<div class="text-box__wrap">
  <h1>Hello</h1>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download