Anupam
Anupam

Reputation: 15620

Bootstrap3 - vertically align label within h2

I am facing an interesting issue with Bootstrap3 where the label ("Name") seems to be aligned at the bottom of the <h2> tag (see the blue box in the image (highlighted by the Chrome dev tool). label inside h2

(From the Bootstrap 3 documentation putting labels inside headings seem to be a suggested way)

I can't figure out how to vertically align the label in center of <h2>. vertical-align doesnt work on h2 it seems. This answer to another SO post suggests changing the line-height but that doesn't seem to be an intuitive approach since it increases the padding on both sides of h2 (basically increasing the size of the h2 block).

This label is inside a table cell whose code is as follows:

<td class="text-right"><h2><span class="label label-default vcenter">Name</span></h2></td>

(vcenter is the class I am trying to use to vertically align)

Upvotes: 1

Views: 994

Answers (3)

tao
tao

Reputation: 90068

It looks like all solutions teach you how to vertically center your .label in the <td>. However, none of them takes into consideration the difference between top and bottom margins on the h2 element.

Basically, you're trying to vertically center with something that's not vertically centered. The only way to account for it is to raise the label with half the margins difference, which should be .5rem. So this will most likely to the job:

h2 > .label { 
   position: relative;
   top: -.5rem;
}

If it doesn't, you have stronger CSS rules applying and I'll need to take a look at them. Feel free to change -.5rem to whatever works for you (in rem or px).


Another approach is to use any vertical centering technique and make the top and bottom margins equal on td>h2 elements:

td>h2 {  margin-top: 1rem; margin-bottom: 1rem; }

After this, most of the other answers will work.

Upvotes: 2

Lalji Tadhani
Lalji Tadhani

Reputation: 14159

add valign middle for td

<td valign="middle" class="text-right"><h2><span class="label label-default vcenter">Name</span></h2></td>

or

add this css

.table tbody>tr>td.vert-align
{
    vertical-align: middle;
}

<td  class="text-right vert-align"><h2><span class="label label-default vcenter">Name</span></h2></td>

Upvotes: 0

pan.goth
pan.goth

Reputation: 1485

You can add display: flex to the headline tag and then center its children vertically:

h2 {
  display: flex;
  align-items: center;
  
  /* Just for presentation */
  background: #ececec;
  height: 100px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<td class="text-right">
  <h2><span class="label label-default vcenter">Name</span></h2>
</td>

Upvotes: 1

Related Questions