1
\$\begingroup\$

I've been trough a few css tutorials. I've also been using basic css for a while now.

My question, How do you decide witch css to use. For instance. If you want a div box to show on the left. You can either use.

float: left;

or

position: absolute;

Another one would be, if you have a paragraph tag inside a div and you want to set its width or height. Do you use

width: auto;
height: auto;

or

width: 100%;
height: 100%;

or

padding: 5px;
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

I'm afraid that there's no 'good' answer here. There are many ways to achieve a certain effect, but they are dependent on the context.

Floated containers differ from the ones that are positioned absolutely. An absolutely positioned container is 'taken out of the layout' - that means e.g. that if you have 2 divs in a parent div and you set position absolute on one, the other one is going to fill the whole parent and the absolutely positioned one is going to be 'on top' of it (provided it has a width & height set, has a higher z-index or is placed last in DOM, but that's another story). If in the same situation you float one of the divs (and it has width set), the other one will 'stick' to it, but again, it (the second div) has to fulfill some criteria (e.g. if it has width set to 100% or 'clear' property set to both or left/right, it will not stick to the other one)

As for width - if an element is a block element or it has display:block set, width: 100% will expand it to be as wide as the closest ancestor that has position:relative or position:absolute set (this might be a little tricky), whereas width:100% on inline elements will not do anything.

width:100% will probably not work as you expect if you have padding set on the element (element will be to wide).

width:auto behaves differently on floated an non floated, block elements...

There are just too many variations. The same solution works in some cases, but doesn't work in others. It's rarely possible to say 'this is just going to work' if you don't look at what's happening to the rest of the page.

\$\endgroup\$
0
\$\begingroup\$

As Chris' long-winded answer demonstrates, deciding between float and absolute positioning depends on the circumstances.

padding works really well with p tags because it adapts regardless of the amount of text.

I recommend this:

p {padding: 8px;}

or this:

p {padding: 1em;}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.