如何在h1背景内垂直居中

时间:2017-06-02 09:45:01

标签: css

我在span内有h1,我希望将其垂直居中于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>

3 个答案:

答案 0 :(得分:1)

只需将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>

答案 1 :(得分:0)

您必须使用与height相同的widthborder-radius属性来获得正确的圈子并移除padding-left

你可以使用flex来更新css,因为我在下面发布了

h1 {
  background-color: green;
  vertical-align: middle;
}

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

答案 2 :(得分:0)

&#13;
&#13;
h1 {
  background-color: green;
  position:relative;
}
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;
    position:absolute;
    top:50%;
    transform:translate(0,-50%);
}
&#13;
<h1>Title <span>i</span></h1>
&#13;
&#13;
&#13;