html - 如何在按钮内垂直对齐谷歌图标? (ie11)

标签 html css button

我在按钮内的某些谷歌图标的垂直对齐方面遇到了问题。我尝试使用填充和边距,但无法解决问题。

这是问题的屏幕截图:如您所见,图标位置略高:

screenshot

这是 html 的一部分,每个按钮都差不多:

<div id="mainToolbar">
    <button id="buttonPencil" data-tool="yes" data-type="draw" title="Use pencil" class="button" onclick="changeTool(0);">
        <i class="material-icons">brush</i>
    </button>
</div>

这是按钮的 css:

.button {

    margin: auto;
    display: inline-block;
    margin-top: 5px;

    color: black;
    border: 0px solid grey;
    border-radius: 6px;

    background-color: #EFEFEF;

    text-align: center;
    text-decoration: none;
    cursor: pointer;

    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
    z-index: 4;
    vertical-align: middle;

}

.button {
    width: 50px;
    height: 40px;
}

.button:hover {
    background-color: #aaaaaa !important;
    color: white !important;
}

最后是 div 的 css:

#mainToolbar {
    position: absolute;
    top: 0px;
    left: 0px;
    height: 520px;
    width: 60px;
    z-index: 10;
    text-align: center;

}

如何将图标放在按钮的正中间(垂直和水平)?谢谢。

最佳答案

您可以使用绝对定位和平移来将图标定位在正中间。请务必在 button 上添加 position:relative,以便图标相对于按钮定位。

.button {

    margin: auto;
    display: inline-block;
    margin-top: 5px;

    color: black;
    border: 0px solid grey;
    border-radius: 6px;

    background-color: #EFEFEF;

    text-align: center;
    text-decoration: none;
    cursor: pointer;

    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
    z-index: 4;
    vertical-align: middle;
    
}

.button {
    width: 50px;
    height: 40px;
    position: relative;
}

.button:hover {
    background-color: #aaaaaa !important;
    color: white !important;
}

.button:active i{
    /*for push effect on click*/
    transform: translate(-45%, -45%);
}

.button i {
  /*horizontal and vertical centering*/
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

#mainToolbar {
    position: absolute;
    top: 0px;
    left: 0px;
    height: 520px;
    width: 60px;
    z-index: 10;
    text-align: center;

}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">
<div id="mainToolbar">
    <button id="buttonPencil" data-tool="yes" data-type="draw" title="Use pencil" class="button" onclick="changeTool(0);">
        <i class="material-icons">brush</i>
    </button>
</div>

解释: top:50%position: absolute 会将图标向下移动父级高度的 50%。具有 -50% 的 translateY 会将图标向上移动其高度的一半,以便其在中间与其中心对齐。与水平居中类似。

关于html - 如何在按钮内垂直对齐谷歌图标? (ie11),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49363742/

相关文章:

javascript - 动画没有按预期工作

java - Android:不同屏幕尺寸无法显示相同内容的问题

javascript - 滚动到名称为 "foo"的随机类

python - lxml 移动带有元素的文本

html - 打印 CSS 和 HTML 书籍

java - 使用 JavaFX 检查单击了哪个 Button 对象

HTML + CSS 图像上的文本淡入淡出阻止淡入淡出的发生

html - 图像缩放以适合 Bootstrap 网格

php - jquery加载间隔div flash

CSS 特异性和/或与祖先的继承