AxD
AxD

Reputation: 3158

CSS: How can I have a <div> within a <table> expand the table horizontally?

I have this situation:

On a HTML5 web page there is a <div> inside a <table> which is inside another <div>:

https://jsfiddle.net/35mvqtyn/2/
(This is a quite simplified example to demonstrate the effect. Please don't suggest to update the HTML DOM. I'm purely concerned with CSS here.)


The inner <div>'s width exceeds the browser page width (if it doesn't, resize the browser window appropriately so the inner <div>'s width will exceed the browser window width). No other constraints exist.


  1. Why does the inner <div>'s width overflow? Why doesn't it extend the <table> and outer <div> widths appropriately to fully cover the inner <div>'s width? (What is the CSS spec rule providing for this behaviour?)

  2. How can I have the containing block elements' width extend automatically to fully cover the inner <div>'s width?

Upvotes: 1

Views: 79

Answers (3)

Maaz Bin Khawar
Maaz Bin Khawar

Reputation: 460

The reason that the inner div's width overflow the outer one is because you have explicitly given the width of the inner one. CSS always applies to the more specific properties first. The outer div being a block level element tends to occupy the whole browser width but not the overflown part of the containing element.

To make it occupy the containing element you have to either make it behave as a td element as LJ have mentioned or either avoid using explicit values of width for the inner div.

Upvotes: 1

Cave Johnson
Cave Johnson

Reputation: 6778

To answer your first question and to supplement LJ's answer: Here is the relevant part of the spec to explain why the table expands to contain the inner div and the outer div does not: https://www.w3.org/TR/CSS2/tables.html#auto-table-layout

From the link (emphasis mine):

In this algorithm (which generally requires no more than two passes), the table's width is given by the width of its columns (and intervening borders). This algorithm reflects the behavior of several popular HTML user agents at the writing of this specification. UAs are not required to implement this algorithm to determine the table layout in the case that 'table-layout' is 'auto'; they can use any other algorithm even if it results in different behavior.

Upvotes: 1

jl_
jl_

Reputation: 5539

Style the div to render as a table-cell using display: table-cell;

body > div
{
  margin: 1ex;
  background-color: white;
  display: table-cell;
}

Upvotes: 2

Related Questions