Set CSS 100% Width Minus Padding And Margin

来源:互联网 发布:android 淘宝首页 编辑:程序博客网 时间:2024/05/05 23:49

Set CSS 100% Width Minus Padding And Margin

Styling elements to fluid layout when its parent element has fixed padding or margin always prompts the question: How do I set the width of the child element to 100% minus its parent’s padding and margin?

You can solve it with CSS box-sizing or with play with parent/child padding without having to add extra wrapping elements. The latter approach is preferable since not all current popular browsers support it.

Set Child Elements To 100%

In this example, a parent form has a fixed margin of .6em, we want the form’s child elements (such as label or input fields) to be fluid. So we set the width of these elements to be 100%.

form > * {  width: 100%;}

input box overflowing with width set to 100%

Add Padding to Parent

Yikes, the input boxes with 100% width are now overflowing the parent form container. We want the form child elements’ width to be 100% width minus 1.2em (two .6em) paddings. We could use box-sizing, but that would complicate things with browser support. The easiest way is to add the 1.2em padding value of to the parent element.

form {  padding-right: 1.2em;} form > * {  width: 100%;}

heading has white space on the right due to form padding

This makes all the child elements’ width 100% minus padding and margin.

Add Padding to Some Child Elements

Not all child elements want to have the padding, such as our form heading. It now has 1.2em of white space on the right. No worries, we can add .6em padding on the heading element since CSS box model’s visual width is width + padding + border. This brings us to our final result:

form {  padding-right: 1.2em;} form > * {  width: 100%;} form > .heading {  padding: .6em;}

nice form



参考:http://www.ikelin.com/set-css-width-100-percent-minus-padding-and-margin/

原创粉丝点击