开发者

Vertical-align on h1 just won't work?

I'm trying to align the text in a h1 vertically to the middle, seeing as the text might wrap it needs to look nice whether it's开发者_运维知识库 1 line or 2.

This is the css I use:

h1 {
  font-size: 12pt;
  line-height: 10pt;
  min-height: 30px;
  vertical-align: middle;
}

The html is quite simply:

<h1>title</h1>

No matter what value I enter for vertical-align, the text is always at the top of the h1 element.

Am I miss-understanding the vertical-align property?


No CSS hacks needed. If I understand you correctly, then you can use this CSS:

h1 {
    font-size: 12pt;
    line-height: 10px;
    padding: 10px 0;
}

See demo fiddle which equals a minimum height of 30px;

A note about vertical-align: that style only works in conjunction with - and is calculated with regard to - the line-height style. So setting line-height at 10px, putting text with height 12pt leaves no space to align at all. But setting line-height to 30px would result in too much space between more lines of text. This shows a trick for vertical aligning several lines of text, but that is only needed when you have a fixed height container. In this case the container's height (the h1 element) is fluid, so you can use this simple padding solution.


I dont know about vertical align, but if you add height property and set height and line-height properties same you get the vertical align: center effect

h1
{
    font-size: 12pt;
    line-height: 50px;
    height: 50px;
}


Center the H1 title using flexbox align items center and justify content center, see this example:

div {
padding: 1em;
border: 1px dashed purple;
}

h1 {
        display: flex;
        align-items: center;
        justify-content: center;
    }
<div>
<h1>Center this h1</h1>
</div>


Just add a float property and use padding-top: 50% for example:

h1 {
  font-size: 12pt;
  line-height: 10pt;
  min-height: 30px;

  position: absolute;
  float: center; /* If you want it to be centered */
  padding-top: 50%;
}


I used a CSS custom property (variable) and calc

:root {
  --header-height: 100px;
}

* {
  margin: 0;
  padding: 0;
}

header {
  font-size: 16px;
  height: var(--header-height);
  justify-content: space-evenly;
  display: flex;
  border-bottom: 1px solid #000;
}

h1,i {
  font-size: 1.2rem;
  display: inline-block;
  padding-top: calc(var(--header-height) - 1.2rem);
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" rel="stylesheet"/>
<header>
  <img src="https://placekitten.com/100/100" alt="logo" height="100">
  <h1>
  Kitten Stories
  </h1>
  <i class="fas fa-lock"></i>
</header>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜