Royi Namir
Royi Namir

Reputation: 148744

vertical align is not applied?

I have a Div which has display:table

JSBIN

enter image description here

<div class='wrapper'>
   <input type="checkbox" class="b"  />
   <span class="c" >aaa bbb ccc</span>
  </div>

And this css :

.wrapper
{
  display: table; 
  border:solid 1px red;
  height:40px;
  width:200px;
}

.b
{
 border:solid 1px green;
 display: table-cell;
 vertical-align: middle; 
}

.c
{
  display: table-cell;
  vertical-align: middle; 
}

As you can see - Both .b and .c has display: table-cell; vertical-align: middle;

Question

Why does the checkbox is not aligned vertically while the span is ?

NB

I know I can use padding etc to manually alignt the checkbox. But Im looking for the solution with table-cell and vertical align ( which should work)

Upvotes: 1

Views: 133

Answers (2)

Marc Audet
Marc Audet

Reputation: 46825

You need to inherit the height from your table down to your table cells:

.wrapper
{
  display: table; 
  border:solid 1px red;
  height:40px;
  width:200px;
}
.b
{ 
  border:solid 1px green;
  display: table-cell;
  vertical-align: middle; 
  height: inherit;
}
.c
{
  display: table-cell;
  vertical-align: middle; 
  height: inherit;
}

See demo at http://jsbin.com/IdOFUmi/23/edit

The reason is that input elements don't quite behave the same as other inline elements. For some reason, setting a height to the table cell fixes the problem.

The best explanation that I can offer is based on my reading about the CSS Table model and the generation of missing table elements:

http://www.w3.org/TR/CSS2/tables.html#anonymous-boxes

In this case, the input element, being a replaced element, cannot be a table cell. As a result, an anonymous table-cell wrapper is generated internally by the CSS engine.

However, the anonymous table-cell does not seem to recognize the the height of the parent table.

If there is a height specified on the element, then the anonymous table-cell applies it.

The best of evidence for this explanation is that the following CSS also gives the same result:

.b
{ 
  border:solid 1px green;
  /* display: table-cell; OMIT THIS */
  vertical-align: middle; 
  height: inherit;
}

without the explicit display: table-cell property, the anonymous element will be drawn and the height property is needed to get the vertical alignment to work.

Upvotes: 2

Ivan Chernykh
Ivan Chernykh

Reputation: 42196

Try this:

.wrapper
{
  display: table-cell;
  border:solid 1px red;
  height:40px;
  width:200px;
  vertical-align: middle; 
}

.b
{  
  border:solid 1px green;
}

div span
{
  border:solid 1px gray;
}

Working: http://jsbin.com/IdOFUmi/11/edit

You're actually want that .wrapper will behave as table-cell , in this case it will be possible to place its children in the center.

Upvotes: 2

Related Questions