HTML columns layout with fixed height and horizontal scroll

For an android project, I need to show a view (WebView), that dynamically loads content. Content items will be <div class="content-item"> tags that are added by JavaScript to <div class="content-holder"> after page has loaded.

The design is such that:

  • List item
  • Content items will be layed out in fixed-width columns. Content items do not necessarily have same height.
  • Height of any column must not exceed screen height. If a column is full, additional content will be put in next column(create column if necessary). There will be no empty columns. Column must not break inside a content item.
  • Page shall be horizontally scrollable(many columns of fixed width), but not vertically (height does not exceed page).

Any ideas on how to implement using css, javascript?

Answers:

Answer

http://jsfiddle.net/B4RPJ/

You can iterate through the content items, check if they fit in the column, and if they don't, create a new column and move the rest of the items to the new column ... like so:

$(".content-item").each( function() {
    // iterate the content items and see if the bottom is out of the container
     var bottom = $(this).position().top + $(this).height();
    if ( bottom > $(this).parent().height() ) {
        // shift it and following content items to new column
        columnShift( $(this) );
    }
} );

function columnShift( el ) {
    var parent = el.parent();
    var container = $(".content-container");

    // create a new column
    var newCol = $("<div class='content-holder'></div>");

    // get the content items that don't fit and move them to new column
    el.nextAll(".content-item").appendTo( newCol );
    el.prependTo( newCol );

    // widen the parent container
    container.width( container.width() + parent.width() );

    // add the new column to the DOM
    parent.after( newCol );
}

with html

<div class="content-container">
    <div class="content-holder">
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
        <div class="content-item"></div>
    </div>
</div>

with an arbitrary number of .content-item divs, containing an arbitrary amount of content

and css of

.content-holder {
    float: left;
    width: 300px;
    height: 300px;
    border: 1px solid #000000;
    overflow: hidden;
    margin: 5px;
    padding: 10px;
}

.content-item {
    max-height: 280px;
    overflow: hidden;
}

I'm sure you can make the code more clever, but this should be a start

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.