Span in h2 tag. Auto adjust width

user1410644 picture user1410644 · Nov 7, 2013 · Viewed 9k times · Source

Here is the HTML part:

<div class="container">
    <h2>Some text<span></span></h2>
</div>

CSS for the elements:

.container {
width: 533px;
}

.container h2 {
color: #ec1c24;
font-size: 48px;
text-transform: uppercase;
font-family: "Open Sans Extrabold";
letter-spacing: -3px;
}

.container h2 span {
background: none repeat scroll 0 0 #ec1c24;
float: right;
height: 34px;
margin-top: 16px;
width: 38%;
}

What I'm trying to do is to make the span adjust it's size to the text lenght. With this CSS if the text is too long, the span goes below but it should just shrink.

Here's an example:

http://jsfiddle.net/SCj5Z/

Answer

Besat picture Besat · Nov 23, 2016

Using flex display you can achieve this. Container display should be flex and the span child attribute could be 1 (or basically any other number since we don't have any other flex child). with using flex we set the span size to fill the empty space and because h2 size is fix (which is size of the text) span will fill all empty space.

you can read more about flexbox here: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Hope this help..

HTML:

<div class="container">
    <h2>Some text<span></span></h2>
</div>

CSS:

.container {
     width: 533px;
}

.container h2 {
    display: flex;
    align-items: center;
}
.container h2 span {
    content:"";
    flex: 1 1 auto;
    border-top: 3px solid #2B3F4F;
    margin-left: 10px;
    margin-right: 5px;
    margin-top: 4px;
}

http://jsfiddle.net/besatzardosht/SCj5Z/75/