简体   繁体   中英

Why aren’t these two `<p>` and `<h3>` elements vertically aligned?

I wrote this code, also available on JSFiddle :

 * { box-sizing: border-box; } body { font-family: 'Roboto Slab', serif; font-size: 18px; line-height: 1.6; } .wrapper { width: 100%; max-width: 1000px; margin: 0 auto; /* Not spacing to top and bottom and auto spacing to left and right*/ padding: 0 20px; } div { margin: 10px; padding: 10px; } h1 { font-size: 36px; text-align: center; } h3, p { max-width: 80ch; margin-left: auto; margin-right: auto; } h3 { font-weight: 400; font-size: 24px; } p { font-weight: 300; text-align: justify; text-justify: auto; } 
 <div class="wrapper"> <div> <h1>Welcome! <span>I'm glad you're here.</span></h1> <h3>My name is Andrés-J. Cremades, and I'm an Interaction/UI Designer.</h3> <p>Usability obsessed interaction designer. Building a UX Designer career founded on strong technological knowledge. Creative and perfectionist by nature with a particular interest in graphic design and HCI with proven working team skills. </p> </div> </div> 

And I don't understand why the <p> and <h3> elements aren't aligned vertically when the browser window is expanded completely .

The thing is that I set a maximum text width of 80 characters and to center it I wrote this first and it worked:

p {
  font-weight: 300;
  max-width: 80ch;
  text-align: justify;
  text-justify: auto;
  margin-left: auto;
  margin-right: auto;
}

Then I wanted the <h3> element to be vertically aligned with the new position of <p> so I modified the code like this:

h3, p {
  max-width: 80ch;
  margin-left: auto;
  margin-right: auto;
}

h3 {
  font-weight: 400;
  font-size: 24px;
}

p {
  font-weight: 300;
  text-align: justify;
  text-justify: auto;
}

I tried to set a margin-left value for <h3> and it worked. Why margin-left and margin-right set a auto don't work on <h3> as on <p> ? What am I doing wrong?

As users @FabioManzano and @benvc pointed ( see comments under the question ), the problem is this declaration:

max-width: 80ch;

80ch is a font-relative length, resulting in a different max-width for those elements - affecting your margin-left: auto; and margin-right:auto; results. [@benvc]

I want to limit text lines length under 80 characters but I had to find another way to do it.

I read the recommendations from this article about how to set a text line length limit properly, and I used px instead of ch . Now they are vertically aligned:

h3, p {
  max-width: 504px;
  margin-left: auto;
  margin-right: auto;
}

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