简体   繁体   中英

Best way to make responsive full page?

I am trying to make a website using a single image as background then add content over it. So far, I was able to achieve this using background-size: cover, however I am having a lot of difficulty when it comes to vertically aligning my content to the middle of the page (every vertical aligning solution seems to involve height being known at some point...)

Looking at some websites doing what I am trying to do (like www.novactive.ca/en), I realized that the height of the image was being adjusted when I would adjust my browser size. I don't know how this is being done but I do suspect some javascript is involved...

So I am wondering if I have been trying this correctly or if there are better, easier way to achieve this ?

Use https://css-tricks.com/perfect-full-page-background-image/ Then you need to absolutely position the text on top of the image, give it 100% width and text-align center it. Change the vertical height with top.

div {
    height: 100vh;
    width: 100%;
    background: url(images/bg.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
.text {
    position: absolute;
    z-index: 10;
    top: 40vh;
    width: 100%;
    text-align: center;
}

I would suggest using flexbox. ( Handy guide .) It allows you to center things without knowing the height. It's modern, and it's supported by all major browsers (Safari, however, still requires a -webkit- flag before the CSS lines...).

You could set the container's height and width to cover the whole page (using viewport units ) and display flex. Then, use the align-items and justify-content attributes to center it. Like this:

 .container { height: 100vh; width: 100vw; background: #ccc url(images/bg.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; display: -webkit-flex; display: flex; -webkit-justify-content: center; justify-content: center; -webkit-align-items: center; align-items: center; } .container > div { width: 200px; height: 200px; -webkit-flex: 1; flex: 1; display: -webkit-flex; display: flex; -webkit-justify-content: center; justify-content: center; -webkit-align-items: center; align-items: center; } 
 <html> <body> <div class="container"> <div>Some text</div> </div> </body> </html> 

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