Michal Foksa Michal Foksa - 1 year ago 78
CSS Question

JavaScript, AngularJS: How do I know if element is larger than its container?

Let’s say I have a title in h1 element (any element would do). Its content is dynamic (do not know length of the title). It is supposed to be displayed in one line. h1 is in a DIV (let’s call it a container) of limited size.

How do I know if element (h1) overflows its container (DIV)?

So that if it overflows I would apply a CSS class to deal with the situation. For example I would scroll hidden content of h1 into view.

  • Width of the container is defined are relative to the screen size.


#container {
width: 60%;
background-color: gray;
height: 50px;
// overflow: hidden;
position: relative;

h1 {
overflow: hidden;
height: 100%;
margin: 0;
line-height: 50px;

<div id="container">
<h1>a soft white or grey mineral consisting of hydrated calcium sulphate. It occurs chiefly in sedimentary deposits and is used to make plaster of Paris and fertilizers, and in the building industry.</h1>

Best solution would be if it could be used in: primary in
, secondary in
directives, but any of following technologies are also good:
AngularJS directive

Answer Source

Here is my solution in AngularJS directive. It does not rely on parent element:

var myDirective = angular.module('myDirective', []);
myDirective.directive( 'myDirective' , ['$timeout' , function($timeout) {
    return {
        link: function (scope , element , attrs) {

            // Wait few milliseconds until element is re-rendered 
            // so that element properties reflect content size.
            $timeout( function(){
                if (element[0].scrollWidth > element[0].offsetWidth){
                    // overflow
            }, 200); // $timeout
        } // link
    }; // return
}]); // myDirective

NOTE: Parent element must have restricted size otherwise it will adjust to the content and element will never overflow.

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