Detect if div has more than one row

How to determine if a div has more than one row? I mean like this:

div :multiline { ... } 

I would like to format the content according to the number of lines (1 or more)

+8
html css
source share
3 answers

If you want to use Javascript / JQuery, you can check the height of the div and see if it is larger if it was with only one line of text. Of course, this is not very convincing, but I do not know another way.

+2
source share

I would not name this solution as much as what could potentially lead to a solution. I thought your question was interesting; so I decided to play a little with CSS.

This is what I came up with.

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

This works best if the single-line content is not near the full width of the container.

Quick notes:

  • I noted some cases of crashes due to the fact that single-line content approaches the full width of the container. (The distance from the full width causing erroneous visual effects depends on the browsers tested in Chrome 33, Firefox 25, and Internet Explorer 11).
  • It uses calc() ( support list )
  • It uses :before pseudo-class ( support list )
  • Tracking the width of content requires the use of an internal inline-block element.
  • This requires the parent to have a known width.
  • This only applies to indentation, which is the OP state 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; } 
+7
source share

I'm not sure if you can manage this with CSS, but you should be able to do this with jQuery. I have to admit that my jQuery is small and I am studying it, so take it with a lot of salt. You can use the height of the property to find the height of the div and add the necessary styles depending on the height of the div.

 $( "div" ).ready( function test(event) { var heightOfDiv = $( document ).height(); if (heightOfDiv > 15){ $("div").css({ backgroundColor: "green" });} } ); 
+1
source share

All Articles