Search code examples
javascripthtmlcssmultiple-columnscss-multicolumn-layout

flow 2 columns of text automatically with CSS


I have the code similar to the following:

<p>This is paragraph 1. Lorem ipsum ... </p>
<p>This is paragraph 2. Lorem ipsum ... </p>
<p>This is paragraph 3. Lorem ipsum ... </p>
<p>This is paragraph 4. Lorem ipsum ... </p>
<p>This is paragraph 5. Lorem ipsum ... </p>
<p>This is paragraph 6. Lorem ipsum ... </p>

I'd like to, without markup if possible, cause this text to flow into two columns (1-3 on the left, 4-6 on the right). The reason for my hesitation to add a column using a <div> is that this text is entered by the client via a WYSIWYG editor, so any elements I inject are likely to be killed later or inexplicably.


Solution

  • Using jQuery

    Create a second column and move over the elements you need into it.

    <script type="text/javascript">
      $(document).ready(function() {
        var size = $("#data > p").size();
     $(".Column1 > p").each(function(index){
      if (index >= size/2){
       $(this).appendTo("#Column2");
      }
     });
      });
    </script>
    
    <div id="data" class="Column1" style="float:left;width:300px;">
    <!--   data Start -->
    <p>This is paragraph 1. Lorem ipsum ... </p>
    <p>This is paragraph 2. Lorem ipsum ... </p>
    <p>This is paragraph 3. Lorem ipsum ... </p>
    <p>This is paragraph 4. Lorem ipsum ... </p>
    <p>This is paragraph 5. Lorem ipsum ... </p>
    <p>This is paragraph 6. Lorem ipsum ... </p>
    <!--   data Emd-->
    </div>
    <div id="Column2" style="float:left;width:300px;"></div>
    

    Update:

    Or Since the requirement now is to have them equally sized. I would suggest using the prebuilt jQuery plugins: Columnizer jQuery Plugin

    http://jsfiddle.net/dPUmZ/1/