将内联块元素居中,并在 td 内部使用链接

Center an inline block element with a link inside of a td

本文关键字:td 并在 内部 链接 元素      更新时间:2024-05-11

编辑:这是一个JSBIN链接:https://jsbin.com/zapuvupato/edit?html,css,js,output 是否有帮助

我拼命地试图使一个元素居中。我尝试文本对齐:在 td 外部/内部的div 中居中。它在链接和文本的样式类中设置。

看起来正在应用文本对齐,但它没有做我想要的,即将整个内联块居中,而不仅仅是内部的链接/文本。

如果我无法使其工作,我正在考虑使用 HTML 按钮。

td.TableButtonStyle {
    display: inline-block;
    border-radius: 10px;
    text-align: center;
    vertical-align: middle;
    margin-top: 5px;
    margin-bottom: 5px;
    margin-left:auto; 
    margin-right:auto;
    color: white;
    background-color: rgb(240,80,40);
    font-weight: bold;
}
.TableButtonStyle a
{
    color:white;
    text-align:center;
}
.Bold
{
    font-weight: bold;
}
th.thCells{
    text-align:center;
    vertical-align:middle;
    font-size: 13pt;
    margin: 0px 5px;
}
td.TableCells {
    text-align:center;
    vertical-align:middle;
    font-size: 13pt;
    padding: 15px 25px;
    margin: 10px 50px;
}
</style>
<table style = "margin: 10px 0px">
    <tr>
        <th class = "TableCells thCells Bold" style = "padding: 0px 15px">Deduction per Pay Period</th>
    </tr>
    <tr>
        <td id = "button1" class = "TableButtonStyle" style = "font-size: 14pt; padding: 15px 25px"></td>
    </tr>
</table>
<script>
    var buttonText1 = "<a href='"javascript: giveButton('"+suggestedAnnualAmt1+"'); onclick:Incr1();'">$"+suggestedAmtPPP1+"</a>";
document.getElementById("button1").innerHTML = buttonText1;
</script>

您可能不应该将<td>元素设置为按钮。 我强烈建议给你的<a>和你的<td>相同的风格,然后从TD中删除样式,告诉<td> text-align:center;

我已将<td>类更改为其他类(.center-inside(

<td id = "button1" class="center-inside" style = "font-size: 14pt; padding: 15px 25px"></td>

然后将CSS更改为样式按钮(并添加了一些填充以使其再次变大(

td.center-inside {
  text-align:center
}
.TableButtonStyle {
    display: inline-block;
    border-radius: 10px;
    text-align: center;
    vertical-align: middle;
    margin-top: 5px;
    margin-bottom: 5px;
    margin-left:auto; 
    margin-right:auto;
    color: white;
    background-color: rgb(240,80,40);
    font-weight: bold;
    padding:20px;
}

然后我将.TableButtonStyle类添加到 javascript 中的按钮中

 var buttonText1 = "<a class='TableButtonStyle' href='"javascript: giveButton('"+suggestedAnnualAmt1+"'); onclick:Incr1();'">$"+suggestedAmtPPP1+"</a>";

https://jsbin.com/mezudaciqi/1/edit?html,css,js,output

你 td 没有占用表格的整个宽度。我可能错误地理解了你的问题。但是,如果您希望"a"在您的"td"中居中。您应该将 td 更改为以下(只是添加宽度(。

<td id="button1" class="TableButtonStyle" style="font-size: 14pt; padding: 15px 25px; width:100%">