igogra
igogra

Reputation: 465

How to center a span vertically inside a h1 background

I have a span inside a h1 and I would like to center it vertically in the h1 background.

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>

Upvotes: 0

Views: 452

Answers (3)

LKG
LKG

Reputation: 4192

You have to use equal height and width property with border-radius to get proper circle and remove padding-left

You can use flex for it and update css as i posted below

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>

Upvotes: 0

Pete
Pete

Reputation: 58432

Just add vertical-align:middle; to it's styles:

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>

If that isn't central enough (it can be based on you font size), you can use flex for true centering - the following also centres the i in the circle:

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>

Upvotes: 1

Name
Name

Reputation: 408

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%);
}
<h1>Title <span>i</span></h1>

Upvotes: 0

Related Questions