如何将文本对齐到按钮的中间

41

你能帮我编写下面的代码吗?

这是我的当前代码

<div id="loginBtn" class="loginBtn"><span>Log in</span></div>

在 HTML 页面中有一个 class 为 loginBtn 的 div 标签和一个文本为 "log in" 的 span 标签。

.loginBtn {
    background:url(images/loginBtn-center.jpg) repeat-x;
    width:175px;
    height:65px;
    margin:20px auto;
    border-radius:10px;
    -webkit-border-radius:10px;
    box-shadow:0 1px 2px #5e5d5b;
}

我使用了1像素的图片创建了一个按钮。现在我无法将“登录”文本放置在图片中间,是否有人可以帮我完成代码?

文本显示在左上角。请帮助我。


在你的 CSS 中添加 text-align: center; 应该可以解决问题。 - Sachin Prasad
1
使用 button.style.padding = '0px' - onmyway133
5个回答

35

您可以使用 text-align: center; line-height: 65px;

演示

CSS

.loginBtn {
    background:url(images/loginBtn-center.jpg) repeat-x;
    width:175px;
    height:65px;
    margin:20px auto;
    border-radius:10px;
    -webkit-border-radius:10px;
    box-shadow:0 1px 2px #5e5d5b;
    text-align: center;  <--------- Here
    line-height: 65px;   <--------- Here
}

1
仅适用于单行文本,无法处理多行文本。 - Teo Mihaila

29

这比“行高”更可预测。

.loginBtn {
    background:url(images/loginBtn-center.jpg) repeat-x;
    width:175px;
    height:65px;
    margin:20px auto;
    border-radius:10px;
    -webkit-border-radius:10px;
    box-shadow:0 1px 2px #5e5d5b;
}

.loginBtn span {
    display: block;
    padding-top: 22px;
    text-align: center;
    line-height: 1em;
}
<div id="loginBtn" class="loginBtn"><span>Log in</span></div>

编辑(2018):使用flexbox

.loginBtn {
    display: flex;
    align-items: center;
    justify-content: center;
}

3

有时候可以通过调整内边距来解决问题...如果你能够操作它,那么它应该能够解决你的问题。

<style type=text/css>

YourbuttonByID {Padding: 20px 80px; "for example" padding-left:50px; 
 padding-right:30px "to fix the text in the middle 
 without interfering with the text itself"}

</style>

它对我有用


2
我认为您可以使用填充(Padding),例如:希望这个能帮到您。
.loginButton {
    background:url(images/loginBtn-center.jpg) repeat-x;
    width:175px;
    height:65px;
    margin:20px auto;
    border-radius:10px;
    -webkit-border-radius:10px;
    box-shadow:0 1px 2px #5e5d5b;
    <!--Using padding to align text in box or image-->
    padding: 3px 2px;
}

0

你可以直接使用

margin: auto;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接