Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Layout a table by DIV elements

Tags:

html

css

I'm interested how could I create a table like layout working only with div elements. I read a lot about display and float style attributes and I think this code should layout content as I want, but I see a table with the second row moved to one position below.

I expect to see:

left1 right1
left2 right2

but I see

left1 
left2 right1
      right2

Here my CSS

.big {
    display: inline-block;
}

.small {
    display: block;
}

.left {
    display: inline;
}

.right {
    display: inline;
    float: right;
}

And here my html file:

<div class="big">
<div class="small">
    <div class="left">left1</div>
    <div class="right">right1</div>
</div>
<div class="small">
    <div class="left">left2</div>
    <div class="right">right2</div>
</div>

I managed to create the table (add rule width: 100px to the .small selector) but I don't want to specify width of my DIV elements, because they could have different width.

Thanks

like image 407
AVokin Avatar asked Jan 21 '12 23:01

AVokin


1 Answers

If it's a true table layout, it's appropriate to use an html table. If it is not a true table layout, here's what you need in your CSS if you were to keep the HTML unchanged:

.small {float:left; clear: both;}
.left {float:left: clear: both;}
.right {float:left;}

"clear: both" is sort of like a carriage return (ding! for all you with memory of typewriters) "float:left" puts stuff next to each other horizontally instead of the natural vertical stacking of box elements (like divs).

For my own table-ish CSS layouts, I use only two classes, "row" and "column", as follows:

/* Standard CSS for div tables.  By Tom Haws
 * Overview:
 * 1. a row is a box element that wants all its children to be
 *    arranged in a (horizontal) row
 *    and is itself a new line rather than a continuation of a line.
 * 2. a column is a box element that wants all its children to be
 *    arranged in a (vertical) column
 *    and is itself a continuation of a line unless it is 
 *    the first column in a row.
 * 
 * */
/* Any child of a row AND any column class that is anything but first-child 
 * represents another column continuing the same row 
 * */
.row>*, .column
{
    float: left;
}
/* Every first child of a row and every column that is a first child of any parent 
 * represents a new row (first column) 
 * */
.row>*:first-child, .column:first-child 
{
    clear: both; 
    float: left;
}
/* All rows and all children of a column are a new line.
 * */
.row, .column>*
{
    clear: both;
    float: left;

}

Here's how I'd do your little example:

<div class="row">
    <div>left1</div>
    <div>right1</div>
</div>
<div class="row">
    <div>left2</div>
    <div>right2</div>
</div>

Feel free to ask any follow-ups about the nuances of the CSS markup and what it's doing.

like image 93
Tom Haws Avatar answered Nov 09 '22 07:11

Tom Haws