css - 如何在 h1 背景中垂直居中跨度

标签 css

我在 h1 中有一个 span,我想将它在 h1 背景中垂直居中。

h1 {
  background-color: green;
}
span {
    font-size: 8.5px;
    color: #fff;
    display: inline-block;
    width: 10px;
    height: 15px;
    padding-left: 5px;
    border: 1px solid #fff;
    border-radius: 50%;
    margin-left: 10px;
    cursor: pointer;
}
<h1>Title <span>i</span></h1>

最佳答案

只需添加 vertical-align:middle; 到它的样式中:

h1 {
  background-color: green;
}
span {
    font-size: 8.5px;
    color: #fff;
    display: inline-block;
    width: 10px;
    height: 15px;
    padding-left: 5px;
    border: 1px solid #fff;
    border-radius: 50%;
    margin-left: 10px;
    cursor: pointer;
    vertical-align:middle;
}
<h1>Title <span>i</span></h1>

如果这还不够居中(它可以基于您的字体大小),您可以使用 flex 实现真正的居中——以下也将 i 在圆圈中居中:

h1 {
  background-color: green;
  
  /*add this*/
  display:flex;
  width:100%;
}
span {
    font-size: 8.5px;
    color: #fff;
    width: 15px;
    height: 15px;
    border: 1px solid #fff;
    border-radius: 50%;
    margin-left: 10px;
    cursor: pointer;
    
    /*use this for vertical centering*/
    align-self:center;
    
    /*use this to center the i*/
    display: inline-flex;
    justify-content:center;
    align-items:center;
}
<h1>Title <span>i</span></h1>

关于css - 如何在 h1 背景中垂直居中跨度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44325788/

相关文章:

javascript - 使用 Onclick 事件将 div 移动到容器左侧的任何选项

php - php for 循环内的 HTML 标签不采用或添加动态 css 和 div 标签

html - 是否有仅针对 Mac 上的 Chrome 的 CSS hack?

html - 固定 div 从父级获取宽度为 100%

css - 当另一个 :checked 时定位一个元素

css - 加载 CSS 和性能

jquery - 创建带有下一个和上一个按钮的图像查看器弹出窗口

html - ie7 和 google adsense 绝对定位

html - 如何在输入下创建带有两个按钮的搜索框?

html - 在 IE 中,带有边界半径的模糊背景不是像素完美的顶部偏移