Simulating 2 columns for 4 successive divs - css

I have 4 successive divs:
<div class="container">
<div class="child">A</div>
<div class="child">B</div>
<div class="child">C</div>
<div class="child">D</div>
</div>
Assuming each child div has varying content, of different heights, and a margin added for clarity, it displays as follows:
Without changing the HTML in any way (no adding classes to the divs, no adding intermediary column divs), I would like to achieve this layout:
The order in which the divs are placed does not matter much.
I've tried things along the lines of:
.child { width: 50%; }
.child:nth-child(even) { float: left; }
.child:nth-child(odd) { float: right; }
But the alignnments are off. Does any CSS wizard have an idea?

Does this work?
DEMO
.container {
width:220px; /* (child width)x2 + (child margin)x4 */
}
.child {
margin:5px;
background-color:#FF0080;
width:100px;
}
.child:nth-child(even) {
float: left;
}
.child:nth-child(odd) {
float: right;
}

Well you could use CSS columns, which has good partial support across browsers (primarily prefixed though), but full support is not so great.
Give them a try:
.container {
-webkit-column-width: 250px;
-moz-column-width: 250px;
column-width: 250px;
width: 520px;
background: yellow;
}
.child {
background: red;
margin-bottom: 10px;
display: inline-block;
width: 100%;
}
Take a look at this jsfiddle for a demonstration: http://jsfiddle.net/xwwe3/ (complete with My First Colours to demonstrate what is happening).
The columns are set to 250px wide, which I found the .child didn't obey until given display: inline-block; width: 100%;. Then the width of .container is set to 520px to give the columns a gutter width of 10px with two columns (250 * 2 + 10 = 520)
So depending on whether you think the support is acceptable for your use case is up to you. Tweaking the heights of the .child elements does make some weird stuff happen, but I'd suggest you read up further on CSS columns and try and work out what is going there.
Alternatively, jQuery masonry is a popular way of achieving this.

Related

Css column layout - inline block elements, what is percent width relative to?

I'm not sure I understand how css column layout is supposed to work.
I have a straightforward html
<div class="container">
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
</div>
and css
.block {
background-color: blue;
width: 50em;
height: 10px;
margin: 2px;
display: inline-block;
}
.container {
border: 1px solid black;
display: inline-block;
column-count: 2;
-moz-column-count: 2;
-webkit-column-count: 2;
}
This works as expected with the elements flowing downwards and then over into a second column.
Now what if I change the width value of .block to a percentage width? All my widths are tiny. They still are clearly relative to something since shrinking and growing the percentages changes the width proportionately but I have no idea what 100% corresponds to.
What is the percentage width relative to?
The width is relative to the column pseudo-element inserted by the browser:
http://www.w3.org/TR/css3-multicol/
In the traditional CSS box model, the content of an element is flowed into the content box of the corresponding element. Multi-column layout introduces a new type of container between the content box and the content, namely the column box (or column for short). The content of a multicol element is flowed into its column boxes.
(Emphasis mine.)
So, the percentage width you're asking for is relative to the implicit column boxes.
Browser Support
As I noted in my comment support for column-count etc is poor today. Except where you really need a specific feature of CSS multicolumn, I find it easier to just use the old inline-block approach. Works in every browser in use today, easy to figure out.
http://jsfiddle.net/b9chris/nt83M/
.block {
background-color: blue;
width: 45%;
height: 10px;
margin: 2px;
display: inline-block;
vertical-align: top;
}
.container {
border: 1px solid black;
width: 200px;
display: inline-block;
}
<span class=container>
<span class=block></span>
<span class=block></span>
<span class=block></span>
<span class=block></span>
<span class=block></span>
</span>
Two important caveats:
For old IE support to work properly you need to use tags that are inline by default, like span. Using a tag that's block by default, like div, will look great in Chrome etc but fail in IE8.
You need to set vertical-align: top in the inner tags to get things to work the way you'd expect them (otherwise everything acts like vertical-align: bottom).
Essentially how column layouts work is you have a container that a width and you split that container into columns. When you decide how many columns you want for your design you assign each of those columns a percentage. Then you float those columns next to each other.
So if you have a 12 column layout the column classes would be as follows:
.col-1 { width: 4.8076923077% }
.col-2 { width: 13.4615384615% }
.col-3 { width: 22.1153846154% }
.col-4 { width: 30.7692307692% }
.col-5 { width: 39.4230769231% }
.col-6 { width: 48.0769230769% }
.col-7 { width: 56.7307692308% }
.col-8 { width: 65.3846153846% }
.col-9 { width: 74.0384615385% }
.col-10 { width: 82.6923076923% }
.col-11 { width: 91.3461538462% }
.col-12 { width: 100%; margin: 0 }
The above columns take into account margins and padding, but here's a fiddle that lays it out.
Parent element width within a content column refers to the column width, a property that defaults to auto. A columnar element is either defined by column-width or column-count (but not both, column-count overrides any column-width value if they are both non-auto). So in your example, providing column-count is causing an automatically generated width to be presented as container width.
source - right above example IX here: http://www.w3.org/TR/2011/CR-css3-multicol-20110412/
Column boxes act as the containing block for their content. That is,
column boxes behave like block-level, table cell, and inline-block
boxes as per CSS 2.1, section 10.1, item 2 [CSS21]. However, column
boxes do not establish containing blocks for elements with ‘position:
fixed’ or ‘position: absolute’.

balanced alternating column layout in CSS3

I'm trying create a balanced (2-) column-layout.
The content is not text but blocks and varies in height.
The content should be placed alternatingly left and right, as long as "left" and "right" have (roughly) the same height..
I.e. in this image:
The space between 1 and 3's shouldn't be there.
Or in this image:
the 2's should stand alone on the right side and the 1, 3's and 4 should stand on the left side (without space between them).
I tried using "floating <li>'s" like this:
HTML:
<ol class="context">
<li class="gruppe">1</li>
<li class="gruppe">2.0<br />2.1</li>
<li class="gruppe">3.0<br />3.1</li>
<li class="gruppe">4</li>
</ol>
CSS:
ol.context
{
border: 1px solid #048;
list-style: none;
margin: 0;
padding: 0 0 8px 0;
overflow: auto;
}
li.gruppe
{
background: #048;
color: white;
float: left;
font: bold 32px Arial, sans-serif;
margin: 1px;
text-align: center;
width: calc(50% - 2px);
}
(See attempt 1 and attempt 2)
I have also tried to use column's (column-count: 2; column-fill: auto;) but this does not fill the columns left-to-right first. (It fills top-to-bottom first.)
Is this even possible without JavaScript?
I would say this is not possible without JS. Here is a fiddle I made based on an article from Ben Holland. At least to me looks like what you are after.
http://jsfiddle.net/QWsBJ/2/
HTML:
<body onload="setupBlocks();">
<div class="block">
<p>***Content***</p>
</div>
<div class="block">
<p>***Content***</p>
</div>
<div class="block">
<p>***Content***</p>
</div>
<div class="block">
<p>***Content***</p>
</div>
<div class="block">
<p>***Content***</p>
</div>
</body>
CSS:
.block {
position: absolute;
background: #eee;
padding: 20px;
width: 300px;
border: 1px solid #ddd;
}
JS:
var colCount = 0;
var colWidth = 0;
var margin = 20;
var blocks = [];
$(function(){
$(window).resize(setupBlocks);
});
function setupBlocks() {
colWidth = $('.block').outerWidth();
colCount = 2
for(var i=0;i<colCount;i++){
blocks.push(margin);
}
positionBlocks();
}
function positionBlocks() {
$('.block').each(function(){
var min = Array.min(blocks);
var index = $.inArray(min, blocks);
var leftPos = margin+(index*(colWidth+margin));
$(this).css({
'left':leftPos+'px',
'top':min+'px'
});
blocks[index] = min+$(this).outerHeight()+margin;
});
}
Array.min = function(array) {
return Math.min.apply(Math, array);
};
Updated: I believe this is almost impossible to achieve with CSS only. There are many different solutions, but they all require some compromises unless you are willing to use JavaScript or some server-side code.
Using CSS columns
Here's an alternate fiddle using reordered blocks. Here's a fiddle demo using CSS columns without reordering.
You can use CSS colunms to change your block flow to vertical unless you alter the order of their output. If you can output odd numbers first, then even numbers, you win.
<div class="wrapper">
<div class="block1">1</div>
<div class="block3">3</div>
<div class="block2">2</div>
<div class="block6">4</div>
</div>
.wrapper {
column-count: 2;
column-width: 100px;
-moz-column-width: 100px;
-webkit-column-width: 100px;
width: 260px;
}
div {
border: 1px solid #999;
display: inline-block;
margin: 10px;
width: 100px;
}
.block1 { height: 100px; }
.block2 { height: 130px; }
.block3 { height: 150px; }
.block4 { height: 100px; }
This solution is not compatible with IE9 and below.
Block Height Known
If you do know your block heights you can solve this problem by using absolute positioning.
block1 {
height: 100px;
position: absolute;
left: 0;
top: 0;
}
block2 {
height: 110px;
position: absolute;
left: 0;
top: 100px; /* The height of the div above it */
}
A big drawback is dynamic content; we seldom know block height. So this solution is very limited in its application unless you are willing to calculate the height block height.
If you are willing to use JS
Use a plugin like Masonry. Both in vanilla js or jQuery flavour.
Other Options
This leaves you with the following options that require some compromises.
Group your blocks into columns. See this Fiddle for a demo. This will alter the flow of your blocks to vertical, then horizontal.
Use display: inline-block; vertical-align: top; on your blocks. This will leave some white space below your blocks.
Force the height of your blocks, rendering this a non-issue. For blocks with additional content use the overflow property to allow in-block scrolling.
As others have commented, you could attempt to calculate the height of the blocks on the server.
You could try a mix of flex and float (only tested in Firefox/IE10 and safari 5.1.7 , cause to my own opinion, CSS is not your solution)
http://codepen.io/gcyrillus/pen/zgAiw
But, in any CSS case you choose, the best is to relay on the mansonry script.
CSS is not really adapted to this kind of layout. At this time you have many CSS method for layout and basicly: display and float.
You can easily use this together within your html tree structure but this methods are not meant to be mixed. A boxe will be floatting, an inline-level-box or block-level-box and each are suppose to interact in the flow.
Float, breaks a line before itself after a non floatting element or slides down untill it has enough room, that you dispatch right/left via CSS r not.
inline-block moves away from floatting elements and breaks a line if not enough room left, floatting elements among inline-blocks will keep breaking a line before floating.
Column CSS will fill columns with content one by one. see : http://codepen.io/gcyrillus/pen/AtazJ
Inline-flex elements seems to work with floatting elements ... but is it suppose to untill it's a validated rule ?
What seems to be wised to me , is to used a javascript for the layout expected and relay on float or display:inline-block + width as a fall back.
Last solution is to think this ahead on your server side and dispatch your items in 2 containers with another appropriate markup if that is possible ( no idea of your real life content dispatched in your ol li ).
The CSS for the FLEX test :
li.gruppe
{
background: #048;
color: white;
font: bold 32px Arial, sans-serif;
text-align: center;
box-sizing:border-box;
border-bottom:1px solid white;
border-bottom:1px solid white;
display: -webkit-inline-flex;
display: -moz-inline-flex;
display: -ms-inline-flex;
display: inline-flex;
width:50%;
}
li:nth-child(even){
float:right;
clear:right;
border-left:1px solid white;
margin-top:0;
}
EDIT: This is an interesting solution, but unfortunately it does not solve the problem that was asked for.
The solution I propose here puts subsequent elements into alternating columns, so: 1 -> left, 2 -> right, 3 -> left, 4 -> right, etc.
This is a interesting problem by itself, but not what was asked for.
Thanks to #Nils in the comments for pointing this out.
Original answer
Here is my attempt with flex!
https://jsfiddle.net/vqLr8t3e/
I am not sure if it works in IE11.
Code
.the-beginning {
background: green;
color: white;
font-weight: bold;
text-align: center;
cursor: pointer;
}
.the-end {
background: red;
color: white;
font-weight: bold;
text-align: center;
cursor: pointer;
}
.container-outer {
overflow: hidden;
}
.container {
display: flex;
flex-wrap: wrap;
flex-direction: column;
max-height: 19999px;
margin-top: -10000px;
}
.container > div {
width: 50%;
box-sizing: border-box;
border: 5px solid grey;
padding: 5px;
background: white;
order: 1;
}
.container > div:nth-child(odd) {
order: -1;
}
.container > div:nth-child(1),
.container > div:nth-child(2) {
margin-top: 10000px;
}
<div class="the-beginning">THE BEGINNING</div>
<div class="container-outer">
<div class="container">
<div>LEFT 0</div>
<div>RIGHT 0<br>RIGHT 0</div>
<div>LEFT 1<br>LEFT 1<br>LEFT 1</div>
<div>RIGHT 1</div>
<div>LEFT 2</div>
<div>RIGHT 2<br>RIGHT 2<br>RIGHT 2</div>
</div>
</div>
<div class="the-end">THE END</div>
Idea
Use flex-direction: column; and flex-wrap: wrap; on the container, and width: 50%; on the items, as a first step towards showing the items in columns.
Use order: -1; and order: 1 to sort odd and even elements into different columns.
Use a gratuitous margin-top: 10000px; on the first element of each column, and a max-height: 19999px; on the container, so that no two such items fit into one column. This will make sure each of these items starts in a new column. Compensate with a negative margin-top on the container. Cut it off with an outer container with overflow: hidden;.
I'm not sure if I got this right . .
"the 2's should stand alone on the right side and the 1, 3's and 4
should stand on the left side (without space between them)."
html:
<div id="box">
<div class="data">1</div>
<div class="data" style="float:right">2<br/>2<br/>2<br/>2</div>
<div class="data">3<br/>3</div>
<div class="data">4</div>
</div>
css:
#box {
width:100%;
height:auto;
float:left;
}
.data {
height:auto;
width:50%;
float:left;
background-color:#ccc;
border-bottom:solid 1px #000;
}
Fid:
http://jsfiddle.net/YdEW9/26/
This is pure css. Everything is floated left then gave inline-css to float:right on the div with (4) 2's
I kinda don't know how to set the inline-css without javascript. Server side maybe? but I doubt you can get the height of the elements.
Well anyway hope this helps.
PURE CSS SOLUTION:
Add the following to your css file:
ol.context li:nth-child(even) {
float: right;
}
DO NOT change your html or anything else.
Result in FF:
--
How it Works
Instead of floating all your elements "left" and creating gaps, we float each container according to the side/column the element they reside in.

Make CSS float columns align at top

http://jsfiddle.net/y88mq/1/
I have a simple layout with three containers: one, two, three. I am trying to get three to align at the top with one. Right now one and two are floated left and three is floated right. I tried combinations of clearing but it didn't seem to work. I would like to get this to work with just CSS.
<div class="left">one</div>
<div class="left">two</div>
<div class="right">three</div>
.left {
background: red;
width: 66%;
height: 200px;
margin-bottom: 10px;
float: left;
}
.right {
background: green;
width: 33%;
float: right;
height: 200px;
}
EDIT: I would like to keep the source order the same
If you must keep the order of the HTML the same, then all i can think of is to use:
position: absolute;
I have made the changes to your Fiddle: http://jsfiddle.net/hRdEf/
Hope that helps.
Due to the nature of CSS and its evil floats, I suggest you rearrange the order of the boxes. This will work fine:
<div class="left">one</div>
<div class="right">three</div>
<div class="left">two</div>
See: http://jsfiddle.net/y88mq/2/
Just place the "right div" at the top of the listed divs.
<div class="right">three</div>
<div class="left">one</div>
<div class="left">two</div>
..//rest of code
http://jsfiddle.net/y88mq/7/
<div class="left">one</div>
<div class="left">two</div>
<div class="right">three</div>
.left {
background: red;
width: 32%;
height: 200px;
margin-right: 20px;
float: left;
}
.right {
background: green;
width: 33%;
float: right;
height: 200px;
}
If you wrap columns one and two in a div, you effectively float the wrapper div and column three side by side and aligned at the top. The wrapper div will hold columns one and two stacked.
Extra advantage of this approach is that you can choose the align columns one and two on one line if there is more space available.
Semantically, your columns would still be in the same order.

3 divs in a container div, make one of them expand if another is cancelled out

I have 3 divs in a parent div which looks like this:
<div id="maincontent>
<div class="left"></div>
<div class="mainbody"></div>
<div class="right"></div>
</div>
The website is 1000px wide.
What I need is to keep the .mainbody div at a minimum of 570px, but have it expand if one of the other 2 divs is removed from the page, which are each given 215px width.
All 3 divs are also floated left.
I tried using min-width and max-width on .mainbody but it doesn't really work. Any other ideas?
My current CSS:
#maincontent {
width: 100%;
overflow: hidden;
}
.left, .right, .mainbody {
float: left;
}
.left, .right {
width: 215px;
}
.mainbody {
width: 570px;
}
CSS Only Solution 1
This assumes the question was accurate in stating "if one of the other 2 divs is removed from the page."
See this fiddle which uses the following code, the key part of which is the :first-child and :last-child change based off your html structure change that you mention. When the left is deleted, the mainbody becomes the first-child and when the right is deleted the mainbody becomes the last-child, so you reset the width if such occurs.
Key CSS
.mainbody {
width: 570px;
float: left;
}
.mainbody:first-child,
.mainbody:last-child {
width: 785px;
}
.left,
.right {
width: 215px;
float: left;
}
CSS Only Solution 2
This accounts for the div remaining, but having no content and being zero width (which is apparently what the situation actually is).
There is a CSS only solution (see this fiddle), but it requires one to restructure the HTML order of the elements and to adjust how they are floated.
Needed HTML Structure (mainbody is last)
<div id="maincontent1">
<div class="left"></div>
<div class="right"></div>
<div class="mainbody"></div>
</div>
Key CSS
.mainbody {
min-width: 570px;
overflow: hidden; /* this triggers expansion between left/right */
}
.left {
width: 215px; /* this is assumed to be zero if no content in div */
float: left;
}
.right {
width: 215px; /* this is assumed to be zero if no content in div */
float: right;
}
Just ad and event to the function. .click(), .ready() etc
if($('.right').is(':visible') == false){
$('.mainbody').width(785+'px');
}
else{ }
or use .size() / .length()

Split Div Into 2 Columns Using CSS

I have been attempting to split a div into two columns using CSS, but I have not managed to get it working yet. My basic structure is as follows:
<div id="content">
<div id="left">
<div id="object1"></div>
<div id="object2"></div>
</div>
<div id="right">
<div id="object3"></div>
<div id="object4"></div>
</div>
</div>
If I attempt to float the right and left divs to their respective positions (right and left), it seems to ignore the content div's background-color. And other code that I have tried from various websites doesn't seem to be able to translate to my structure.
Thanks for any help!
This works good for me. I have divided the screen into two halfs: 20% and 80%:
<div style="width: 20%; float:left">
#left content in here
</div>
<div style="width: 80%; float:right">
#right content in there
</div>
When you float those two divs, the content div collapses to zero height. Just add
<br style="clear:both;"/>
after the #right div but inside the content div. That will force the content div to surround the two internal, floating divs.
Another way to do this is to add overflow:hidden; to the parent element of the floated elements.
overflow:hidden will make the element grow to fit in floated elements.
This way, it can all be done in css rather than adding another html element.
None of the answers given answer the original question.
The question is how to separate a div into 2 columns using css.
All of the above answers actually embed 2 divs into a single div in order to simulate 2 columns. This is a bad idea because you won't be able to flow content into the 2 columns in any dynamic fashion.
So, instead of the above, use a single div that is defined to contain 2 columns using CSS as follows...
.two-column-div {
column-count: 2;
}
assign the above as a class to a div, and it will actually flow its contents into the 2 columns. You can go further and define gaps between margins as well. Depending on the content of the div, you may need to mess with the word break values so your content doesn't get cut up between the columns.
The most flexible way to do this:
#content::after {
display:block;
content:"";
clear:both;
}
This acts exactly the same as appending the element to #content:
<br style="clear:both;"/>
but without actually adding an element. ::after is called a pseudo element. The only reason this is better than adding overflow:hidden; to #content is that you can have absolute positioned child elements overflow and still be visible. Also it will allow box-shadow's to still be visible.
For whatever reason I've never liked the clearing approaches, I rely on floats and percentage widths for things like this.
Here's something that works in simple cases:
#content {
overflow:auto;
width: 600px;
background: gray;
}
#left, #right {
width: 40%;
margin:5px;
padding: 1em;
background: white;
}
#left { float:left; }
#right { float:right; }
If you put some content in you'll see that it works:
<div id="content">
<div id="left">
<div id="object1">some stuff</div>
<div id="object2">some more stuff</div>
</div>
<div id="right">
<div id="object3">unas cosas</div>
<div id="object4">mas cosas para ti</div>
</div>
</div>
You can see it here: http://cssdesk.com/d64uy
Make children divs inline-block and they will position side by side:
#content {
width: 500px;
height: 500px;
}
#left, #right {
display: inline-block;
width: 45%;
height: 100%;
}
See Demo
You can use flexbox to control the layout of your div element:
* { box-sizing: border-box; }
#content {
background-color: rgba(210, 210, 210, 0.5);
border: 1px solid #000;
padding: 0.5rem;
display: flex;
}
#left,
#right {
background-color: rgba(10, 10, 10, 0.5);
border: 1px solid #fff;
padding: 0.5rem;
flex-grow: 1;
color: #fff;
}
<div id="content">
<div id="left">
<div id="object1">lorem ipsum</div>
<div id="object2">dolor site amet</div>
</div>
<div id="right">
<div id="object3">lorem ipsum</div>
<div id="object4">dolor site amet</div>
</div>
</div>
Best way to divide a div vertically --
#parent {
margin: 0;
width: 100%;
}
.left {
float: left;
width: 60%;
}
.right {
overflow: hidden;
width: 40%;
}
Pure old school CSS
I know this post is old, but if any of you still looking for a simpler solution.
#container .left,
#container .right {
display: inline-block;
}
#container .left {
width: 20%;
float: left;
}
#container .right {
width: 80%;
float: right;
}
If you don't care old browser and need a simple way.
#content {
display: flex;
}
#left,
#right {
flex: 50%;
}
Floats don't affect the flow. What I tend to do is add a
<p class="extro" style="clear: both">possibly some content</p>
at the end of the 'wrapping div' (in this case content). I can justify this on a semantic basis by saying that such a paragraph might be needed. Another approach is to use a clearfix CSS:
#content:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
#content {
display: inline-block;
}
/* \*/
* html #content {
height: 1%;
}
#content {
display: block;
}
/* */
The trickery with the comments is for cross-browser compatibility.
This is best answered here Question 211383
These days, any self-respecting person should be using the stated "micro-clearfix" approach of clearing floats.
Make font size equal to zero in parent DIV.
Set width % for each of child DIVs.
#content {
font-size: 0;
}
#content > div {
font-size: 16px;
width: 50%;
}
*In Safari you may need to set 49% to make it works.
Divide a division in two columns is very easy, just specify the width of your column better if you put this (like width:50%) and set the float:left for left column and float:right for right column.

Resources