I am sure this problem has been asked before but I cannot seem to find the answer.
I have the following markup:
<div id="foo">
<div id="bar">
here be dragons
</div>
</div>
My desire is to make foo to have width of 600px
(width: 600px;
) and to make bar have the following behaviors:
padding-left: 2px;
padding-right: 2px;
margin-left: 2px;
margin-right: 2px;
outerWidth: 100%;
In other words instead of setting width of bar to 592px
I would like to set the outer width of bar to 100%
so that it is computed to 592px
. The importance here is that I can change foo's width to 800px
and bar will calculate when rendered instead of me having to do the math for all these instances manually.
Is this possible in pure CSS?
Some more fun with it:
#bar
is a table? #bar
is a textarea? What if #bar
is an input?
What if #foo
is a table cell (td
)? (Does this change the problem or is the problem identical?)
So far the table#bar
, input#bar
has been discussed. I have not seen a good solution for textarea#bar. I Think a textarea with no border/margin/padding with a div
wrap might work with the div
styled to work as borders for the textarea
.
This question is related to
css
So after research the following is discovered:
For a div#bar
setting display:block; width: auto;
causes the equivalent of outerWidth:100%;
For a table#bar
you need to wrap it in a div with the rules stated below. So your structure becomes:
<div id="foo">
<div id="barWrap" style="border....">
<table id="bar" style="width: 100%; border: 0; padding: 0; margin: 0;">
This way the table takes up the parent div 100%, and #barWrap
is used to add borders/margin/padding to the #bar
table. Note that you will need to set the background of the whole thing in #barWrap
and have #bar
's background be transparent or the same as #barWrap
.
For textarea#bar
and input#bar
you need to do the same thing as table#bar
, the down side is that by removing the borders you stop native widget rendering of the input/textarea and the #barWrap
's borders will look a bit different than everything else, so you will probably have to style all your inputs this way.
box-sizing: border-box;
width: 100%;
padding: 5px;
box-sizing: border box; makes it so that padding, margin and border are included in the width calculations.
Use the styles
left: 0px;
or/and
right: 0px;
or/and
top: 0px;
or/and
bottom: 0px;
I think for most cases that will do the job
almost there, just change outerWidth: 100%;
to width: auto;
(outerWidth is not a CSS property)
alternatively, apply the following styles to bar:
width: auto;
display: block;
Source: Stackoverflow.com