Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align like a table but with CSS?

Tags:

html

css

layout

Is it possible to align the following 2 rows like a table ? The first row is a h2 because it is the title and the rest are lists. The first column should be quite wide but the rest can be as wide as the text inside. The columns must fill the width of the div.

<div>
<h2 class="header1">
<span class="span1">one</span>
<span class="span2">two</span>
<span class="span3">three</span>
<span class="span4">four</span>
</h2>
<ul><li>
<span class="span5">five</span>
<span class="span6">six</span>
<span class="span7">seven</span>
<span class="span8">eight</span>
</li></ul>
</div>
div {width: 500px;}
h2 span, li span {float: left; width: auto; white-space: nowrap;}

Example:

Example

like image 927
Jane Watson Avatar asked Sep 08 '11 14:09

Jane Watson


People also ask

Can you use CSS to style a table?

CSS provides a number of attributes for styling tables. These attributes allow you to—among other things—separate cells in a table, specify table borders, and specify the width and height of a table. This tutorial will discuss, with examples, how to style a table using CSS.

How do you center align a table in CSS cell?

We use the CSS property text-align, to center align text in table cells. We use inline, internal style sheet for text alignment in table cells. The text-align property of CSS sets the alignment of the content in <th> and <td>. By default, the content of <th> are center-aligned and the content of <td> are left-aligned.

How do I fix the alignment in CSS?

Center Align Elements To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.


2 Answers

The HTML

<div class="table-like">
  <div>
    <span>one</span>
    <span>two</span>
    <span>three</span>
    <span>four</span>
  </div>
  <div>
    <span>five</span>
    <span>six</span>
    <span>seven</span>
    <span>eight</span>
  </div>
</div>

The CSS

.table-like {
  display: table;
  width: 500px;
}

.table-like div { 
  display: table-row;
}

.table-like div span { 
  display: table-cell;
}

/* add borders */
.table-like,
.table-like div span {
  border: 1px solid black;  
}

/* bold on 1st row */
.table-like div:nth-child(1) {
  font-weight: bold;
}

jsFiddle Demo

like image 72
Simone Avatar answered Sep 24 '22 23:09

Simone


Honestly, if you're trying to display tabular data, use a table. There's nothing wrong with tables, only when you're using them to position non-tabular content. If you need help formatting a table, edit your question.

like image 43
Wex Avatar answered Sep 24 '22 23:09

Wex