方法以使子 div 适合其父 div 的宽度

我正在寻找一个解决方案,以适应一个孩子的 div到它的父母的 width

我在这里看到的大多数解决方案 不能跨浏览器兼容(例如,IE<=8不支持 display: table-cell;)。

image showing intended result with a child div being the full size of it's parent, with inner padding

253943 次浏览

The solution is to simply not declare width: 100%.

The default is width: auto, which for block-level elements (such as div), will take the "full space" available anyway (different to how width: 100% does it).

See: http://jsfiddle.net/U7PhY/2/

Just in case it's not already clear from my answer: just don't set a width on the child div.

You might instead be interested in box-sizing: border-box.

If you put position:relative; on the outer element, the inner element will place itself according to this one. Then a width:auto; on the inner element will be the same as the width of the outer.

In your image you've putting the padding outside the child. This is not the case. Padding adds to the width of an element, so if you add padding and give it a width of 100% it will have a width of 100% + padding. In order to what you are wanting you just need to either add padding to the parent div, or add a margin to the inner div. Because divs are block-level elements they will automatically expand to the width of their parent.

You don't even need width: 100% in your child div:

http://jsfiddle.net/DanielDZC/w2mev/1/

In case you want to use that padding space... then here's something:

http://jsfiddle.net/qD4zd/

All the colors are background colors.

You can use box-sizing css property, it's crossbrowser(ie8+, and all real browsers) and pretty good solution for such cases:

#childDiv{
box-sizing: border-box;
width: 100%; //or any percentage width you want
padding: 50px;
}

Fiddle