CSS: Line break after first word for any content

5.7k Views Asked by At

I need to leave only one word on the first line regardless of content, so no additional markup possible.

I've tried to do this using word-spacing with ::first-line pseudo-element. This works fine in Firefox or IE, but fails in WebKit browsers (tested in latest versions of Chrome, Opera and Safari).

Also, setting word-spacing for the whole element works just fine.

Am I missing something or it just doesn't work in WebKit?

Example below does exactly what I want if opened in Firefox or IE, but not in WebKit browsers.

.outer {
  width: 100px;
  border: 1px solid black;
  height: auto;
  margin: 0 0 20px;
}

.inner {
  display: inline-block;
}

.with-first-line::first-line {
  word-spacing: 200px;
}

.whole {
  word-spacing: 200px;
}
<div class="outer">
  <span class="inner with-first-line">long line with words</span>
</div>

<div class="outer">
  <span class="inner whole">long line with words</span>
</div>

1

There are 1 best solutions below

1
l.g.karolos On

So , I think that will do

(function () { 
    var node = $(".with-first-line").contents().filter(function () { return this.nodeType == 3 }).first(),
        text = node.text(),
        first = text.slice(0, text.indexOf(" "));
    
    if (!node.length)
        return;
    
    node[0].nodeValue = text.slice(first.length);
    node.before('<span class="first">' + first + '</span><br/>');
})();
.first { color: red; font-weight: bold; }

.outer {
  width: 100px;
  border: 1px solid black;
  height: auto;
  margin: 0 0 20px;
}

.inner {
  display: inline-block;
}

.with-first-line::first-line {
  word-spacing: 200px;
}

.whole {
  word-spacing: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer">
  <span class="inner with-first-line">long line with words</span>
</div>

<div class="outer">
  <span class="inner whole">long line with words</span>
</div>