简体   繁体   中英

How to align text according to above text in CSS?

I have a div of width 50vw wide, containing some text, with some other text below that I want aligned to the right, as follows:

https://jsfiddle.net/hadr4ytt/1/

Here is the current CSS:

div {
  width:50vw;
  margin-left:7.4vw;
  } 

 h3{
   text-align:right;
 }

I was wondering if it was possible to align the h3 text so that the end character is always lined up to the end character of the h2 text. Also, if the h2 text was to be expanded so that it spanned multiple lines, is it possible to line up the end character of h3 with the right most character of h2 (the text is not justified so depending on the word length different lines will have different lengths).

Added display: inline-block; to the div.

 div { margin-left: 7.4vw; display: inline-block; } h3 { text-align: right; } 
 <div> <h2> Some text here </h2> <h3> Other text here </h3> </div> 

As far as I understand all you need is to add text-align: right; to a h2 element and that will give you your desired result.

If the outer div must remain at 50vw, the solution is to add a new element inside the div that you can align the headers to.

 div { width: 50vw; margin-left: 7.4vw; } hgroup { display: inline-block; } h3 { text-align: right; } 
 <div> <hgroup> <h2> Some text here. </h2> <h3> Other text here </h3> </hgroup> </div> 

Edit: Oh, my apologies to @David Hedlund, who already posted a demo in a comment. I didn't see that before posting my answer.

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