JavaScript:100% 减去像素
我有一个设置为 100% 的 div,但为了适合我需要它的位置,我确实需要将大小设置为 100% 减去 5px。我希望我可以通过使用 javascript 来完成此任务。
我当前的代码看起来像:
document.getElementById('div').style.width='100%';
但我想做的是:
document.getElementById('div').style.width='100% - 5px';
任何人都可以帮助我完成这个任务。谢谢。
I have a div that is set to 100% but in order to fit where i need it to go i really need the size to be 100% minus 5px. I was hoping i could accomplish this by using javascript.
My current code looks like :
document.getElementById('div').style.width='100%';
but what i am trying to do is something like:
document.getElementById('div').style.width='100% - 5px';
Can anyone help me accomplish this. Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
遗憾的是你不能像这样混合单位。如何使用填充:
或者在你的 CSS 中:
你不需要宽度 100% 和填充,因为这样盒子的实际内容部分将是 100%,填充在其之外(以及填充之外的任何边框)。如果您使用默认宽度,它应该占据父元素的整个宽度,然后填充将内容向内推。
如果你在想“等一下:我不能使用填充来定位,因为我需要在分配的空间内进一步填充”,那么我想,尽管我讨厌鼓励 divitis,你可以创建一个额外的全宽容器 div和 5px 填充,然后将你的 div 放入该容器中...
(PS 我不建议为元素提供像“div”这样的 ID,这会令人困惑...)
Regrettably you can't mix the units like that. How about using padding:
Or in your CSS:
You don't want width 100% and padding because then the actual content part of the box will be at 100% with the padding outside that (and any border outside the padding that). If you use a default width it should take up the full width of the parent element and then padding pushes the content inwards.
If you're thinking "Wait a minute: I can't use padding for positioning because I need further padding within that allotted space" then I guess, much as I hate to encourage divitis, you could create an extra container div with full width and 5px padding and then put your div inside that container...
(P.S. I don't recommend giving an ID like "div" to an element, it is confusing...)