Flow 2 Columns Of Text Automatically With CSS - Stack Overflow

    1. Home
    2. Questions
    3. Tags
    4. Users
    5. Companies
    6. Labs
    7. Jobs
    8. Discussions
    9. Collectives
    10. Communities for your favorite technologies. Explore all Collectives

  1. Teams

    Ask questions, find answers and collaborate at work with Stack Overflow for Teams.

    Try Teams for free Explore Teams
  2. Teams
  3. Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Get early access and see previews of new features.

Learn more about Labs flow 2 columns of text automatically with CSS [duplicate] Ask Question Asked 14 years, 7 months ago Modified 2 years, 2 months ago Viewed 129k times 80 This question already has answers here: How to make text over flow into two columns automatically (7 answers) Closed 2 years ago.

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.

Share Improve this question Follow edited Oct 27, 2022 at 16:01 TylerH's user avatar TylerH 21.2k76 gold badges79 silver badges110 bronze badges asked Jun 9, 2010 at 20:27 Joe Mastey's user avatar Joe MasteyJoe Mastey 27.1k13 gold badges82 silver badges104 bronze badges 3
  • If you gave them classes it would work, but I think you'd run into the same problem with the WYSIWYG editor – Kerry Jones Commented Jun 9, 2010 at 20:29
  • 3 What about a javascript solution? Count the nodes and put half into each of 2 created divs? – Dan Heberden Commented Jun 9, 2010 at 20:31
  • 1 I don't love the idea of JS for typography, but that's probably the most workable solution so far. Gracefully degrades, too. – Joe Mastey Commented Jun 9, 2010 at 20:41
Add a comment |

8 Answers 8

Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 171

Use CSS3's multi-column layout:

.container { column-count: 2; column-gap: 20px; }

Browser Support (unprefixed):

  • Chrome 50
  • Firefox 52
  • Safari 9
  • Edge 12
  • Opera 11.5
  • IE 10
Share Improve this answer Follow edited Oct 27, 2022 at 16:01 TylerH's user avatar TylerH 21.2k76 gold badges79 silver badges110 bronze badges answered Jun 14, 2010 at 20:59 Glennular's user avatar GlennularGlennular 18.2k9 gold badges60 silver badges77 bronze badges 1
  • 3 Note that this doesn't work very well when there are line breaks in the part where the text goes to the next column. It works, but the second column will look misaligned as the first line is a line break. – Christian Valentin Commented May 26, 2020 at 13:28
Add a comment | 35 +200

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/

Share Improve this answer Follow edited Mar 25, 2013 at 12:17 Anri's user avatar Anri 6,2653 gold badges39 silver badges61 bronze badges answered Jun 14, 2010 at 16:40 Glennular's user avatar GlennularGlennular 18.2k9 gold badges60 silver badges77 bronze badges 2
  • 3 Aside from the issue of creating the column container dynamically (which I can do in jQuery), this assumes a roughly equal content size in each paragraph, which doesn't seem to be the case. This would leave one column potentially far shorter than the other. – Joe Mastey Commented Jun 14, 2010 at 20:42
  • Note! There is good CSS3 support for this now (even in IE), see the next answer below. – rustyx Commented Apr 1, 2014 at 11:01
Add a comment | 22

Automatically floating two columns next to eachother is not currently possible only with CSS/HTML. Two ways to achieve this:

Method 1: When there's no continous text, just lots of non-related paragraphs:

Float all paragraphs to the left, give them half the width of the containing element and if possible set a fixed height.

<div id="container"> <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> </div> #container { width: 600px; } #container p { float: left; width: 300px; /* possibly also height: 300px; */ }

You can also insert clearer-divs between paragraphs to avoid having to use a fixed height. If you want two columns, add a clearer-div between two-and-two paragraphs. This will align the top of the two next paragraphs, making it look more tidy. Example:

<div id="container"> <p>This is paragraph 1. Lorem ipsum ... </p> <p>This is paragraph 2. Lorem ipsum ... </p> <div class="clear"></div> <p>This is paragraph 3. Lorem ipsum ... </p> <p>This is paragraph 4. Lorem ipsum ... </p> <div class="clear"></div> <p>This is paragraph 5. Lorem ipsum ... </p> <p>This is paragraph 6. Lorem ipsum ... </p> </div> /* in addition to the above CSS */ .clear { clear: both; height: 0; }

Method 2: When the text is continous

More advanced, but it can be done.

<div id="container"> <div class="contentColumn"> <p>This is paragraph 1. Lorem ipsum ... </p> <p>This is paragraph 2. Lorem ipsum ... </p> <p>This is paragraph 3. Lorem ipsum ... </p> </div> <div class="contentColumn"> <p>This is paragraph 4. Lorem ipsum ... </p> <p>This is paragraph 5. Lorem ipsum ... </p> <p>This is paragraph 6. Lorem ipsum ... </p> </div> </div> .contentColumn { width: 300px; float: left; } #container { width: 600px; }

When it comes to the ease of use: none of these are really easy for a non-technical client. You might attempt to explain to him/her how to do this properly, and tell him/her why. Learning very basic HTML is not a bad idea anyways, if the client is going to be updating the web pages via a WYSIWYG-editor in the future.

Or you could try to implement some Javascript-solution that counts the total number of paragraphs, splits them in two and creates columns. This will also degrade gracefully for those who have JavaScript disabled. A third option is to have all this splitting-into-columns-action happen serverside if this is an option.

(Method 3: CSS3 Multi-column Layout Module)

You might read about the CSS3 way of doing it, but it's not really practical for a production website. Not yet, at least.

Share Improve this answer Follow edited Jun 14, 2010 at 16:22 answered Jun 14, 2010 at 16:15 Arve Systad's user avatar Arve SystadArve Systad 5,4791 gold badge34 silver badges59 bronze badges 4
  • The columns are in fact ordered, and I cannot expect that they won't clobber the contentColumn containers (in fact I expect that they will get clobbered), unfortunately. CSS3 isn't an option for obvious reasons, so still stuck. – Joe Mastey Commented Jun 14, 2010 at 20:41
  • Maybe you should consider removing the entire column-concept? Would make things a lot easier for both yourself and your client ;-) – Arve Systad Commented Jun 17, 2010 at 15:33
  • Why "not yet practical for a production web site" in 2010? It's practical now, in 2019, isn't it? – ChrisW Commented Jul 18, 2019 at 9:19
  • I guess it is. Back then, not so much, as it was not widely supported among those oldschool browsers of yesteryear. – Arve Systad Commented Jul 19, 2019 at 10:43
Add a comment | 5

Here is an example of a simple Two-column class:

.two-col { -moz-column-count: 2; -moz-column-gap: 20px; -webkit-column-count: 2; -webkit-column-gap: 20px; }

Of which you would apply to a block of text like so:

<p class="two-col">Text</p> Share Improve this answer Follow edited Aug 4, 2013 at 22:13 Brad Larson's user avatar Brad Larson 170k45 gold badges400 silver badges572 bronze badges answered Aug 4, 2013 at 16:06 99freebies.blogspot.com's user avatar 99freebies.blogspot.com99freebies.blogspot.com 1071 silver badge2 bronze badges 1
  • 1 You forgot about IE10+ :-o – Mr. Polywhirl Commented Feb 25, 2015 at 20:42
Add a comment | 3

Not an expert here, but this is what I did and it worked

<html> <style> /*Style your div container, must specify height*/ .content {width:1000px; height:210px; margin:20px auto; font-size:16px;} /*Style the p tag inside your div container with half the with of your container, and float left*/ .content p {width:490px; margin-right:10px; float:left;} </style> <body> <!--Put your text inside a div with a class--> <div class="content"> <h1>Title</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus gravida laoreet lectus. Pellentesque ultrices consequat placerat. Etiam luctus euismod tempus. In sed eros dignissim tortor faucibus dapibus ut non neque. Ut ante odio, luctus eu pharetra vitae, consequat sit amet nunc. Aenean dolor felis, fringilla sagittis hendrerit vel, egestas eget eros. Mauris suscipit bibendum massa, nec mattis lorem dignissim sit amet. </p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer eget dolor neque. Phasellus tellus odio, egestas ut blandit sed, egestas sit amet velit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;</p> </div> </body> </html>

Once the text inside the <p> tags has reached the height of the container div, the other text will flow to the right of the container.

Share Improve this answer Follow edited Dec 10, 2012 at 23:23 Musa's user avatar Musa 97.6k17 gold badges122 silver badges142 bronze badges answered Dec 10, 2012 at 22:58 Abner M's user avatar Abner MAbner M 311 bronze badge Add a comment | 3

Below I have created both a static and dynamic approach at columnizing paragraphs. The code is pretty much self-documented.

Foreward

Below, you will find the following methods for creating columns:

  1. Static (2-columns)
  2. Dynamic w/ JavaScript + CSS (n-columns)
  3. Dynamic w/ JavaScript + CSS3 (n-columns)
Static (2-columns)

This is a simple 2 column layout. Based on Glennular's 1st answer.

$(document).ready(function () { var columns = 2; var size = $("#data > p").size(); var half = size / columns; $(".col50 > p").each(function (index) { if (index >= half) { $(this).appendTo(".col50:eq(1)"); } }); }); .col50 { display: inline-block; vertical-align: top; width: 48.2%; margin: 0; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="data" class="col50"> <!-- 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> <p>This is paragraph 7. Lorem ipsum ...</p> <p>This is paragraph 8. Lorem ipsum ...</p> <p>This is paragraph 9. Lorem ipsum ...</p> <p>This is paragraph 10. Lorem ipsum ...</p> <p>This is paragraph 11. Lorem ipsum ...</p> <!-- data End--> </div> <div class="col50"></div>

Dynamic w/ JavaScript + CSS (n-columns)

With this approach, I essentially detect if the block needs to be converted to columns. The format is col-{n}. n is the number of columns you want to create.

$(document).ready(function () { splitByColumns('col-', 4); }); function splitByColumns(prefix, gap) { $('[class^="' + prefix + '"]').each(function(index, el) { var me = $(this); var count = me.attr("class").split(' ').filter(function(className) { return className.indexOf(prefix) === 0; }).reduce(function(result, value) { return Math.max(parseInt(value.replace(prefix, '')), result); }, 0); var paragraphs = me.find('p').get(); me.empty(); // We now have a copy of the children, we can clear the element. var size = paragraphs.length; var percent = 1 / count; var width = (percent * 100 - (gap / count || percent)).toFixed(2) + '%'; var limit = Math.round(size / count); var incr = 0; var gutter = gap / 2 + 'px'; for (var col = 0; col < count; col++) { var colDiv = $('<div>').addClass('col').css({ width: width }); var css = {}; if (col > -1 && col < count -1) css['margin-right'] = gutter; if (col > 0 && col < count) css['margin-left'] = gutter; colDiv.css(css); for (var line = 0; line < limit && incr < size; line++) { colDiv.append(paragraphs[incr++]); } me.append(colDiv); } }); } .col { display: inline-block; vertical-align: top; margin: 0; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="data" class="col-6"> <!-- 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> <p>This is paragraph 7. Lorem ipsum ...</p> <p>This is paragraph 8. Lorem ipsum ...</p> <p>This is paragraph 9. Lorem ipsum ...</p> <p>This is paragraph 10. Lorem ipsum ...</p> <p>This is paragraph 11. Lorem ipsum ...</p> <!-- data End--> </div>

Dynamic w/ JavaScript + CSS3 (n-columns)

This has been derived from on Glennular's 2nd answer. It uses the column-count and column-gap CSS3 rules.

$(document).ready(function () { splitByColumns('col-', '4px'); }); function splitByColumns(prefix, gap) { var vendors = [ '', '-moz', '-webkit-' ]; var getColumnCount = function(el) { return el.attr("class").split(' ').filter(function(className) { return className.indexOf(prefix) === 0; }).reduce(function(result, value) { return Math.max(parseInt(value.replace(prefix, '')), result); }, 0); } $('[class^="' + prefix + '"]').each(function(index, el) { var me = $(this); var count = getColumnCount(me); var css = {}; $.each(vendors, function(idx, vendor) { css[vendor + 'column-count'] = count; css[vendor + 'column-gap'] = gap; }); me.css(css); }); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="data" class="col-3"> <!-- 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> <p>This is paragraph 7. Lorem ipsum ...</p> <p>This is paragraph 8. Lorem ipsum ...</p> <p>This is paragraph 9. Lorem ipsum ...</p> <p>This is paragraph 10. Lorem ipsum ...</p> <p>This is paragraph 11. Lorem ipsum ...</p> <!-- data End--> </div>

Share Improve this answer Follow edited May 23, 2017 at 12:26 Community's user avatar CommunityBot 11 silver badge answered Feb 25, 2015 at 15:17 Mr. Polywhirl's user avatar Mr. PolywhirlMr. Polywhirl 48.4k12 gold badges93 silver badges143 bronze badges Add a comment | 0

This solution will split into two columns and divide the content half in one line half in the other. This comes in handy if you are working with data that gets loaded into the first column, and want it to flow evenly every time. :). You can play with the amount that gets put into the first col. This will work with lists as well.

Enjoy.

<html> <head> <title>great script for dividing things into cols</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script> <script> $(document).ready(function(){ var count=$('.firstcol span').length; var selectedIndex =$('.firstcol span').eq(count/2-1); var selectIndexafter=selectedIndex.nextAll(); if (count>1) { selectIndexafter.appendTo('.secondcol'); } }); </script> <style> body{font-family:arial;} .firstcol{float:left;padding-left:100px;} .secondcol{float:left;color:blue;position:relative;top:-20;px;padding-left:100px;} .secondcol h3 {font-size:18px;font-weight:normal;color:grey} span{} </style> </head> <body> <div class="firstcol"> <span>1</span><br /> <span>2</span><br /> <span>3</span><br /> <span>4</span><br /> <span>5</span><br /> <span>6</span><br /> <span>7</span><br /> <span>8</span><br /> <span>9</span><br /> <span>10</span><br /> <!--<span>11</span><br /> <span>12</span><br /> <span>13</span><br /> <span>14</span><br /> <span>15</span><br /> <span>16</span><br /> <span>17</span><br /> <span>18</span><br /> <span>19</span><br /> <span>20</span><br /> <span>21</span><br /> <span>22</span><br /> <span>23</span><br /> <span>24</span><br /> <span>25</span><br />--> </div> <div class="secondcol"> </div> </body> </html> Share Improve this answer Follow answered Aug 2, 2012 at 19:28 namretiolnave's user avatar namretiolnavenamretiolnave 8011 gold badge11 silver badges25 bronze badges 1
  • As a side note, you don't even need the conditional, I just added it in case you only want it "overflow" after a certain number as in setting it to 4 before overflowing. – namretiolnave Commented Aug 2, 2012 at 20:44
Add a comment | 0

Maybe a slightly tighter version? My use case is outputting college majors given a json array of majors (data).

var count_data = data.length; $.each( data, function( index ){ var column = ( index < count_data/2 ) ? 1 : 2; $("#column"+column).append(this.name+'<br/>'); }); <div id="majors_view" class="span12 pull-left"> <div class="row-fluid"> <div class="span5" id="column1"> </div> <div class="span5 offset1" id="column2"> </div> </div> </div> Share Improve this answer Follow answered Aug 4, 2014 at 15:29 sjskier's user avatar sjskiersjskier 11 bronze badge Add a comment |

Not the answer you're looking for? Browse other questions tagged or ask your own question.

  • The Overflow Blog
  • Developers want more, more, more: the 2024 results from Stack Overflow’s...
  • How AI apps are like Google Search
  • Featured on Meta
  • The December 2024 Community Asks Sprint has been moved to March 2025 (and...
  • Stack Overflow Jobs is expanding to more countries

Linked

14 How to make text over flow into two columns automatically 5 Bootstrap Writing In Columns (like a newspaper) 6 Multi-column definition list 6 Is it possible to put sections inside container in reStructuredText? 3 Content fill first column then wrap to next 3 flow 3 columns of text automatically with CSS and jQuery 3 CSS3: how to put something at the top of second column? 0 CSS Two text column side by side dynamically 0 How to split into new column via multi-column layout only when text is overflowing 0 Make the text flow from one column to another repetitively See more linked questions 4407 Change an HTML input's placeholder color with CSS 6137 How to disable text selection highlighting 3712 Set cellpadding and cellspacing in CSS? 4274 Is there a CSS parent selector? 3189 Is it possible to apply CSS to half of a character? 3441 How can I change an element's class with JavaScript? 2549 How do I reduce the opacity of an element's background using CSS? 2967 How can I transition height: 0; to height: auto; using CSS? 4598 Setting "checked" for a checkbox with jQuery

Hot Network Questions

  • Can an intelligent agent with aims desire to modify itself to change those aims?
  • Test To Destruction - short story (not the Keith Laumer one)
  • What is a good way to DM searching for something?
  • How to decompose the following rational function into partial fractions?
  • Identifying data frame rows in R with specific pairs of values in two columns
  • Glideslope antenna structure and alignment
  • Should I include my legal name on my CV if my preferred name is not reflected on my diplomas? -- Humanities
  • Mama’s cookies too dry to bake
  • Advice for creating a clean table with tabularray
  • If my mount were to attune to a headband of intellect, could I teach it common (to full understand and work with me as an Intelligent creature)?
  • Can you connect isolated power supplies in series
  • Is there any denomination which officially rejects Young Earth Creationism?
  • In the "His Dark Materials" tv series, how did the staff member have her daemon removed?
  • Free Kei Friday
  • C vs. C++: comparing function pointer tables and switch-case for multiple types support
  • pouring cup modelisation help
  • How to Prevent Distortion When Instantiating Objects with Geometry Nodes in Blender?
  • Recreating lab integrator result in LTspice simulation
  • Most distant visible object in the daytime sky - Venus?
  • Inverting band pass filter circuit not showing theoretical behavior at all in SPICE simulation. What am I missing?
  • Kids' book where a girl trades her heart for a heart made of lead
  • Does the Nondetection 10 feet limit only apply to objects?
  • Heat liquids (water, milk) to specific temperature?
  • Simple autoplay JS slider advice
more hot questions default

Từ khóa » Html Flow Text Into Two Columns