简体   繁体   中英

How to keep text in center of the html section when changing the screen size?

I have implemented a simple web page with 2 sections. In each of this section there is text contains 2 lines. I would like to keep this text in center (margin left, top, right, bottom) in the section when changing the size of the screen (RWD). Eg when I run this web page on the desktop the text in the section will be in center-center of the section and when I run this web page on the smartphone/tablet this text also be in the center of the section. Is it possible to do it? The code is below:

 body { height: 100%; } section { height: 60vh; } section:nth-child(1) { background: white; } section:nth-child(2) { background: #f2efef; } 
  <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <section> John is happy.<br><br> Thank you.<br><br> </section> <section> Have a nice day.<br><br> Good luck.<br><br> </section> </body> </html> 

Thank you for help.

You can use flexbox grid for block alignment.

 body { height: 100%; } section { height: 60vh; display: flex; justify-content: center; align-items: center; } section:nth-child(1) { background: white; } section:nth-child(2) { background: #f2efef; } 
 <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <section> John is happy.<br><br> Thank you.<br><br> </section> <section> Have a nice day.<br><br> Good luck.<br><br> </section> </body> </html> 

I hope this helps you.

in the CSS file you can use the following ways,

section {
  text-align:center;
  height: 60vh;
}

/* or */

section {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60vh;
}

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