Re: margins, ems and context

On 26/01/2011 19:15, Alan Gresley wrote:
> On 27/01/2011 4:51 AM, Alan Gresley wrote:
> <!DOCTYPE html>
>
> <style type="text/css">
> .container p { margin: 1em 3em }
> .container h1 { margin: 1em 1.5em }
> </style>
>
> <div class="container" style="width: 800px; margin: 0 auto; border: 10px
> solid blue;">
> <div style="float:left; width: 100%; background: lime;">Float</div>
> <h1>Heading</h1>
> <p>text</p>
> </div>
>
>
> The only work around that I know of is to wrap the <h1> and <p> in
> another element and apply the padding to it.

Ah, now I understand you.  It's not the use of 100% that's the problem 
(unlike what I claimed in my previous reply when I wasn't aware of your 
use case; although I still very much question the use of 'float', but 
that's a whole different tangent).

I'm presuming that the float represents a navigation bar or something. 
The problem is that this particular block-level element needs to occupy 
the full horizontal space between the borders of the container.

To achieve that, you use padding on the container to set the default 
offset of its children.  Then you give the navbar a 100% width and a 
horizontal padding equal to that default offset,(*) and you should use 
negative horizontal margins on the navbar (which is precisely what 
negative horizontal margins are designed for) to "pull" the navbar 
leftwards over the container's left padding, and to "allow" the navbar 
to sit over the container's right padding.

This is an extremely common design pattern.  It's frequently used for 
call-out boxes on web pages which consist of an image which stretches 
from side to side and some text underneath which is indented from the 
call-out's border:

-------------------
|-----------------|
||               ||
||               ||
||               ||
|-----------------|
|   texty txt a   |
|   foo txt tex   |
|                 |
|   bar txty tx   |
|   txt texty a   |
-------------------


(*)100% width with an added horizontal padding isn't nice either since 
that padding quantity might not be what you /actually/ would like it to 
be (such as zero).  Unfortunately we're stuck with that problem in CSS21 
unless you know the actual width of the container as a length instead of 
as a percentage.

You may be questioning why, then, this technique is "right" and the 
other "wrong", given that this technique also has problems.  I'll try to 
explain this tomorrow; I'm out of time today.

Cheers,
Anton Prowse
http://dev.moonhenge.net

Received on Wednesday, 26 January 2011 19:09:47 UTC