skip to Main Content

How can I vertically align a badge (which is smaller) vertically next to the h1 tag.
I don’t want to put the span tag into the h1 tag for SEO reasons.

Right now it is aligned at the bottom. I want to have it in the middle.

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div style="width:350px;">
  <h1 class="d-inline">This is a Test This is a Test</h1>
  <span class="badge badge-secondary ml-2">My Badge</span>
</div>

Expected result:

enter image description here

2

Answers


  1. You can make the parent flexbox and then align-items: center;

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
    
    <div style="width:350px;" class="d-flex align-items-center">
      <h1 class="d-inline" style="white-space: no-wrap;">This is a Test This is a Test</h1>
      <span class="badge badge-secondary ml-2">My Badge</span>
    </div>

    Note: I’ve added white-space: no-wrap; to the heading to prevent it from wrapping

    Otherwise, if that’s cheating, you can use transform to position it 50% up from the bottom of the last row (so it also works for multiline titles)

    .badge {
      transform:translateY(-50%);
    }
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
    
    <div style="width:350px;">
      <h1 class="d-inline">This is a Test This is a Test</h1>
      <span class="badge badge-secondary ml-2">My Badge</span>
    </div>

    However, this transformation is based on it’s own height, rather than the height of the parent, so it will break when the font size is increased.

    You’re probably best off adding the span to the h1 element as it will give you more control; I’m sure that Google is intelligent enough to understand that pattern.

    Login or Signup to reply.
  2. Play with vertical-align

    .badge.badge-secondary {
      vertical-align: 0.7em;
    }
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
    <div style="width:350px;">
      <h1 class="d-inline">This is a Test This is a Test</h1>
      <span class="badge badge-secondary ml-2">My Badge</span>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search