根据内容的宽度和高度固定位置(而不是100%) [英] Position fixed with width and height based on content (and not 100%)
问题描述
我有一个容器DIV设置为"position:fixed",其中包括另一个div设置为绝对位置.
I have a container DIV set to "position:fixed", that includes another div set to position absolute.
有什么办法可以使包含的div的宽度和高度适合内容,而不总是100%吗?
Is there any way I can make this included div with the width and the height to fit the content, and not always 100%?
这就是我所拥有的: http://jsfiddle.net/ydSqU/
<div class="transparent_background">
<div id="window">hello.</div>
</div>
这就是我想要的: http://jsfiddle.net/3BYPu/(不必手动设置宽度/高度).
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>
推荐答案
aur0n,
如果可能的话,最好的和最简单的方法是使用javascript计算元素的高度和宽度,然后相应地定位内部元素.
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.
要做到这一点,只需将包含元素的宽度除以二,然后将内部元素的 left
值设置为该值减去其自身宽度的一半即可.然后,对高度进行相同操作.
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.
此外,您可能会错过的一件事是您的内部div应该设置为 position:relative
和 display:inline
.您的div拉伸以匹配包含元素的宽度的原因是因为 position:absolute
将元素从正常流程中移出,而 position:relative
将其保留在正常流程中
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.
这是我使用的代码(使用jQuery):
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");
使用此解决方案,您不必手动设置宽度和高度.同样,具有多行文本的内部div也不是问题.
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.
小提琴: http://jsfiddle.net/ydSqU/3/
这篇关于根据内容的宽度和高度固定位置(而不是100%)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!