Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if a div has more than one line

Tags:

html

css

How can I detect if a div has more than one line? I mean like this:

div :multiline {
   ...
}

I'd like to format the content regarding the number of lines (1 or more)

like image 810
Kiss Koppány Avatar asked Apr 06 '14 21:04

Kiss Koppány


2 Answers

I wouldn't call this a solution so much as something that could potentially lead to a solution. I thought your question was interesting; so I decided to play around with CSS for a little bit.

This is what I came up with.

It uses the current width of the internal span (given through inline-block display) to determine the indent width. We use calc() to make the indent 100% minus the parent width of 200px which has our final indent added to it (30px).

It works best if the single-line content does not get near the full width of the container.

Quick Notes:

  1. I've noted some failure cases due to the single-line content getting near the full width of the container. (Distance from the full-width causing erroneous visuals varies between browsers, tested in Chrome 33, Firefox 25, and Internet Explorer 11)
  2. It uses calc() (list of support)
  3. It uses :before pseudo class (list of support)
  4. It requires the use of an internal inline-block element to track content width.
  5. It requires the parent element to have a known width.
  6. This only covers indentation which is what OP States they are trying to achieve in the comments of their post.

HTML Code:

<h1>Success Cases</h1>
<p><span class="indent">Single line Single line</span></p>
<p><span class="indent">The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.</span></p>
<h1>Failure Cases</h1>
<p><span class="indent">Single line Single line Single 1</span></p>
<p><span class="indent">Single line Single line Single line</span></p>

CSS Code:

p {
    background-color: #ccc;
    margin: 10px;
    width: 200px;
}

p > .indent {
    display: inline-block;
}
p > .indent:before {
    background-color: red;
    content: "";
    float: left;
    width: calc(100% - 200px + 30px);
    height: 1em;
}
like image 89
jsea Avatar answered Oct 19 '22 11:10

jsea


If you're willing to use Javascript/JQuery, you could check the height of the div and see if it is greater than it would be with only one line of text. Of course, this isn't very error-proof, but I wouldn't know another way.

like image 41
EagleV_Attnam Avatar answered Oct 19 '22 11:10

EagleV_Attnam