I have a container DIV set to "position:fixed", that includes another div set to position absolute.
Is there any way I can make this included div with the width and the height to fit the content, and not always 100%?
This is what I have: http://jsfiddle.net/ydSqU/
<div class="transparent_background">
<div id="window">hello.</div>
</div>
This is what I would like: http://jsfiddle.net/3BYPu/ (without having to manually set width/height).
<div class="transparent_background">
<div id="window" style="width:30px; height:30px">hello.</div>
</div>
It seems like this should be one of the easiest things to understand in CSS. If you want a block-level element to fill any remaining space inside of its parent, then it's simple — just add width: 100% in your CSS declaration for that element, and your problem is solved.
Syntax: height: length|percentage|auto|initial|inherit; Property Values: height: auto; It is used to set height property to its default value.
Set everything up as you would if you want to position: absolute inside a position: relative container, and then create a new fixed position div inside the div with position: absolute , but do not set its top and left properties. It will then be fixed wherever you want it, relative to the container.
An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element.
aur0n,
If possible, the best and easiest way to do this is to use javascript to calculate the height and width of the elements then position the inner element accordingly.
To accomplish this, you simply take the width of the containing element and divide it by two, then set the left
value of the inner element to that amount minus half its own width. Then, do the same for the height.
Also, one of the things you might have missed is that your inner div should be set to position: relative
and display: inline
. The reason your div is stretching to match the width of the containing element is because position: absolute
takes the element out of normal flow, while position: relative
leaves it in normal flow.
Here is the code I used (using jQuery):
// centering the width
$("#window").css("left", ($(".transparent_background").width()/2)-($("#window").width()/2) + "px");
// centering the height
$("#window").css("top", ($(".transparent_background").height()/2)-($("#window").height()/2) + "px");
With this solution, you don't have to manually set width and height. Also, having an inner div with multiple lines of text will not be a problem.
fiddle: http://jsfiddle.net/ydSqU/3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With