简体   繁体   中英

H2 text width lower than h1 text with

So I have this html code:

<div>
    <h1>My h1 title</h1>
    <h2>This is my h2 text which needs to be center aligned and in the same time not to pass the h1 title width</h2>
</div>

I want this block to look like this one using just css:

h2宽度不应超过h1宽度

Explanation: My h1 will have a bigger font-size and my h2 will have a smaller one. I want that my h2 will be center aligned in the div and the div should have the width of my h1 text. (h1 should stay on 1 line not on many)

How can I achieve this? Thanks

You could try a jQuery plugin called FitText.js . Like the name suggests, it fits text to fill a container, as demonstrated here . Putting both of your headers inside the same div and running $("h1,h2").fitText(); should give them the same width. Check out their Github page for more examples.

Here's a tremendously round about (hacky) way of achieving this with just CSS:

http://codepen.io/anon/pen/waJKGw

div {
  margin:0 auto;
  width:300px;
  text-align:center
}
h1 {
  text-align:justify;
  text-align-last: justify;
  display:block;
  margin-bottom:0;
}
h1:after {
  content: "";
  display: inline-block;
  width: 100%;
  height:0;
}

The H1 is justified to fill out the entire width of your div container.. Meaning if your div is wide and your h1 text is very short, you get something really ugly - but that's for you to figure out with your content.

Then the H2 is just center aligned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM