html - 如何在html按钮中将图标左对齐和文本居中?

标签 html css

你怎么能有一个图标左对齐(按钮最左边)并且文本仍然在按钮中心的按钮?

.GoogleSignIn{
    border-radius: 50px;
    padding: 10px;
    text-align: center;
    align-items: center;
    width: 100%;
    height: 42px;
    font-size: 14px;
    font-weight: 500;
    background-color: white;
    border: none;
    color: black;
    margin-bottom: 10px;
    cursor: pointer;
    outline: none;
    display: flex;
    /* justify-content: center; */
}
.GoogleIcon{
    margin: -40px 0px -12px -440%;
}
.GoogleIconContainer{
    align-self: flex-end;
    display: flex;
}
<button className={classes.GoogleSignIn}>
                    <div className = {classes.GoogleIconContainer}>
                        <img src={GoogleIcon} className = {classes.GoogleIcon}/>
                    </div>
                    Sign in with google
</button>

最佳答案

5 行 CSS 代码和额外的跨度(用于文本)。
** 这个想法对于站点导航栏布局也很有用。

flex container
-- flex item 1 
-- flex item 2
“诀窍”:设置 flex-item-1 margin-right: auto(现在 flex-item-2 移动到右边缘“推送效果”)。
接下来,再使用 margin-right: auto for flex-item-2 (“向右推完美中心”)
enter image description here
片段

button{
  display: flex;  
  align-items: center;
  justify-content: center;
}
button img{
  margin-right: auto;
  border: 1px solid red;
}

button span{
  border: 1px solid red;
  margin-right: auto;
}
<button style="width: 100%;">
  <img src="https://svgshare.com/i/5vv.svg">
  <span>
    Hello world  
  </span>
</button>

<br>
<button style="width: 200px;">
  <img src="https://svgshare.com/i/5vv.svg">
  <span>
    Hello world  
  </span>
</button>
important要获得 “完美的 V/H 对齐” 不要为按钮内的内容添加任何额外的顶部/​​底部边距/填充 - 图标 - 或 - 文本(“著名”错误)。important-2删除 按钮固定高度 (避免溢出问题)。按钮的高度由内容(字体大小、图像)和填充/边框( box-model )声明。如果它对您真的很重要,请设置 min-height ( not 高度)。 splinter 片段示例:

button{
  display: flex;  
  align-items: center;
  justify-content: center;
}
button img{
  margin-right: auto;
  border: 1px solid red;
}

button span{
  border: 1px solid red;
  margin-right: auto;
}
<button style="height: 20px;">
  <img src="https://svgshare.com/i/5vv.svg">
  <span style="font-size: 30px;">
    40px height ==> ovefrlow issues
  </span>
</button>

<br><br><br><br>

<button style="height: 30px; overflow-y: scroll">
  <img src="https://svgshare.com/i/5vv.svg">
  <span style="font-size: 40px;">
    40px height ==> ovefrlow issues
  </span>
</button>

完成 :)
相关(额外阅读):
  • https://css-tricks.com/how-auto-margins-work-in-flexbox/
  • https://www.smashingmagazine.com/2018/08/flexbox-alignment/
  • https://scrimba.com/learn/flexbox
  • 关于html - 如何在html按钮中将图标左对齐和文本居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61159717/

    相关文章:

    javascript - 强制将页面大小调整为特定大小

    html - html中自定义单选按钮的必需属性

    javascript - CHROME 中文件上传输入控件的 onchange 事件错误

    html - 好的 CSS 表格主题工具?

    html - Pseudo Class和Css Role如何应用主题

    html - CSS - 文本与其他 div 中的文本对齐

    javascript - 用鼠标旋转轮盘

    php - 如何清理和存储 WordPress 中包含 HTML 正则表达式模式的用户输入

    jquery - 如何在 CSS 中调整 div 框的大小,使文本无论长度如何都居中

    css - 为每种颜色悬停颜色跨站点