Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable width depending on position?

Tags:

css

If I assign position:absolute to an element, its width will not be variable depending on the text inside.

On the other hand, if I assign position:relative to that element, the width will vary depending on the text inside.

Here I have the fiddle with two menus, each one with a different position property: http://jsfiddle.net/je3PX/4/

What is the cause of this? Why width depends on the position attribute? Im looking to make it vary depending on the text size.

Thanks.

like image 735
Alvaro Avatar asked Feb 14 '26 06:02

Alvaro


1 Answers

The default value for width is auto, meaning it will adapt itself to the layout as required. For block level elements (display:block et al) this means adapting to the parent container, for inline elements (display:inline et al) this means adapting to the content.

The position attribute factors in this in that the value relative does not take the element out of the regular flow layout, and as such the base rules are still maintained. The value absolute does take it out of the regular flow layout, as such there is no longer a parent to base the width on, as such falling back to fit-to-content.

The relevant rules are defined in chapter 10 of the W3 CSS2 specification (too long to quote).

like image 150
Niels Keurentjes Avatar answered Feb 15 '26 19:02

Niels Keurentjes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!