语法:使用变量作为 css 值
尝试使一个盒子在另一个盒子内垂直居中。我知道有 css 可以做到这一点,但我宁愿使用 jquery,更可靠(?)。
var textH = $(".Text").height();
var vertAlign = ((140 - textH)/2);
$(".Text").css({
marginTop: 'vertAlign'
});
不知道我错过了什么细节。输出应该是可用垂直空间的一半(以像素为单位)。
编辑
最初,文本块是一个 div 包含的范围。 div 有一个固定的高度(在本例中为 140 px),文本块(即跨度)的高度将根据其中的文本量而变化。但是,我需要这个文本块是可编辑的。所以我把它改成了文本区域。但是,文本区域尺寸的行为很尴尬,我必须为其设置静态高度和宽度。现在,该文本块的高度不可变,因此它与从中导出边距顶部间距的父级之间的高度没有差异。我应该怎么办?
Trying to keep a box centered vertically within another box. I know there's css that can do this, but I'd rather use jquery, more reliable(?).
var textH = $(".Text").height();
var vertAlign = ((140 - textH)/2);
$(".Text").css({
marginTop: 'vertAlign'
});
Not sure what detail I'm missing. The output should be half the available vertical space, in pixels.
EDIT
Originally, the text block was a span contained by a div. The div had a set height (140 px in this case), and the text block, the span, would be variable height based on how much text was in it. However, I need this text block to be editable. So I changed it to a text area. however, the behavior for the dimensions of the text area is awkward, and I had to set a static height and width to it. Now the height of this text block isn't variable, so there's no difference in height between it and it's parent with which to derive the margin-top spacing from. What should I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
删除
vertAlign
周围的引号尝试上面的代码。它一定对你有帮助。
Remove quotes surrounding
vertAlign
Try the above code. It must help you.
如果您想做多种样式,则可以选择:
optionally if you'd like to do more than one style:
您需要指定单位,否则您的浏览器将无法判断您想要像素、em还是苹果。此外,您可能想要进行一些范围检查,您不希望
vertAlign
成为消极的。You need to specify the unit, otherwise your browser won't be able to tell whether you want pixels or em or apples.Also you might want to do some range checking, you do not want
vertAlign
to be negative.