PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 16, 2022

[FIXED] How to vertically align a badge next to a multiline heading element's last line?

 November 16, 2022     badge, bootstrap-4, css, vertical-alignment     No comments   

Issue

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/bootstrap@4.0.0/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


Solution

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

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/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/bootstrap@4.6.1/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.



Answered By - Joe Czucha
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing