【问题标题】:How do I center a button that's not in a DIV element?如何将不在 DIV 元素中的按钮居中?
【发布时间】:2016-03-13 20:19:45
【问题描述】:

这是我的代码

<input type="submit" value="Submit Order" 
       onclick="this.value='Uploading..';
                google.script.run.withSuccessHandler(fileUploaded)
                .uploadFiles(this.parentNode);
                return false;">

我不能把它放在 DIV 元素中,否则它不能正常工作,所以我想知道如何才能使这个按钮居中。

编辑:这是我的网页整体代码:https://jsfiddle.net/n0ya9tbq/

我不能把它放在 DIV 元素中的原因是因为我使用的是 Google Apps 脚本,如果我把它放在 GAS 中,我会遇到这个错误:google.script.run not working: Uncaught InvalidArgumentError: Failed due to illegal value in property: 0

【问题讨论】:

  • 您通常通过将 其父级的内容居中来居中内联和内联块元素。
  • 无论如何,我们需要更多代码/完整(但最少,例如onclick 代码似乎不相关?)重现您的场景。如果您分享您的尝试和研究,这也会有所帮助:有很多方法可以解决这个问题,具体取决于上下文,一种解决方案可能比另一种更可取。
  • onclick 可能是相关的,他说它在 div 中不起作用......为什么不呢?
  • 居中发生在 parent 对象上。所以,除了body 标签之外,没有任何真正的父级,这可能很难。另外,如果将其放在div 中,为什么该功能不起作用?

标签: html css


【解决方案1】:

你可以改变显示属性

input[type="submit"] {
  display: block;
  width: 50%;
  margin: 0 auto;
}
<input type="submit" value="Submit Order" 
       onclick="this.value='Uploading..';
                google.script.run.withSuccessHandler(fileUploaded)
                .uploadFiles(this.parentNode);
                return false;">

【讨论】:

  • 在没有固定宽度的情况下也能正常工作。
  • 是的,您只需要更改display 属性。请接受我的回答!
  • 这会根据页面大小而不是容器的宽度大小使按钮居中。如果我最小化页面或缩小页面,按钮的位置就会改变。
  • 您可以以像素为单位设置宽度而不是百分比...当然如果您设置width: 50%;,则按钮宽度基于其代表 100% 的父级...
  • 让宽度改变按钮的大小而不是按钮所在的位置,这对我来说就是这样
【解决方案2】:

只需在输入标签中包含一个 ID <input type="submit" value="Submit Order" id='centeredbutton' class='buttoncenter' onclick="this.value='Uploading..'; google.script.run.withSuccessHandler(fileUploaded) .uploadFiles(this.parentNode); return false;">

然后使用css:

`input#centeredbutton {
position: fixed;
bottom: 50%;
right: 50%;
}`

或者,如果您有多个想要居中的按钮:

`input.buttoncenter {
position: fixed;
bottom: 50%;
right: 50%;
}`

【讨论】:

    猜你喜欢
    • 2013-02-24
    • 2023-03-29
    • 2011-11-25
    • 2023-01-27
    • 2015-02-06
    • 2015-11-23
    • 2016-03-10
    • 1970-01-01
    相关资源
    最近更新 更多