CSS 获取div元素的宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4680785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getting width of a div element
提问by gyaani_guy
HTML:
HTML:
<a id="postanad" href="postad.php">Make a Post</a>
CSS:
CSS:
#header #postanad {
position: absolute;
top: 50px;
left: 250px ;
background: #000 url(postad.gif) repeat-x 0% 100%;
font: bold 19px Tahoma, 'trebuchet MS', Sans-serif;
padding: 5px;
}
How do I determine the size in pixels/ems that the div element is taking so that I can make the background image postad.gif to be of the same width?
如何确定 div 元素采用的像素/em 大小,以便我可以使背景图像 postad.gif 具有相同的宽度?
Just to be clear I don't want to determine the width dynamically , but just want to know how much space it is taking so that I can draw a background image in PS.
为了清楚起见,我不想动态确定宽度,但只想知道它占用了多少空间,以便我可以在 PS 中绘制背景图像。
采纳答案by Chandu
If you are interested in measuring the width of an element on a page you can use Measure IT addon on Firefox:
如果您有兴趣测量页面上元素的宽度,您可以在 Firefox 上使用 Measure IT 插件:
回答by atfergs
If you're comfortable with jQuery, you can just use $("#postanad").width().
如果您对 jQuery 感到满意,则可以使用 $("#postanad").width()。
回答by Gordon Gustafson
CSS isn't a 'programming language'. You can't really make decisions, gather data, or manipulate anything the language wasn't designed to do. If you want to do that, javascript is your best choice.
CSS 不是“编程语言”。您无法真正做出决策、收集数据或操作该语言并非旨在执行的任何操作。如果你想这样做,javascript 是你最好的选择。
What exactly do you want to have happen with the background? We might be able to help you get a CSS only solution if we know your requirements.
你到底想在背景中发生什么?如果我们知道您的要求,我们可能能够帮助您获得仅 CSS 的解决方案。
回答by stoneMonkey77
Is the div in question being redrawn dynamically? Because if not, the easiest thing is to set the height and width in the #header #postanad style.
有问题的 div 是动态重绘的吗?因为如果没有,最简单的方法是在#header #postanad 样式中设置高度和宽度。
回答by Amit
The jQuery way, like @orthod0ks said would be to use the width() function.
The CSS way would be to declare a width
and height
jQuery 的方式,就像@orthod0ks 所说的那样,是使用 width() 函数。CSS 方法是声明一个width
和height
OR, another CSS way would be to:
或者,另一种 CSS 方式是:
You can also put a background on the div (like background: red;
), take a screenshot, and paste into PS to see how big it is.
也可以在div上放个背景(比如background: red;
),截个图,贴到PS里看看有多大。
Lastly, Firefox has a plugin called (MeasureIt). It is rather useful for determining sizes of things in terms of pixels. So you should look into that if both solutions are not viable for you.
最后,Firefox 有一个名为 (MeasureIt) 的插件。它对于根据像素确定事物的大小非常有用。因此,如果这两种解决方案都不适合您,您应该考虑一下。
Good luck!
祝你好运!