Positioning image horizontally center and make height 100% of viewport

前端 未结 4 697
长发绾君心
长发绾君心 2021-01-03 02:53

I have a an image taking up the entire height of the viewport. The image height should span the entire viewport height (100%) so that it will fit to the screen it is viewed

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-03 03:08

    I'm assuming your main is going to contain other items, so with a second wrapper div:

    Some text.
    And Some More.

    You can set this css:

    body {
        overflow: hidden;
    }
    
    .bg{
        width: 100%;
        height: 100%;
        text-align: center;
        position: fixed;
    }
    
    .bg img {
        max-height: 100%;
        height: auto;
    }
    
    .bg span {
        display: block;
        position: absolute;
        width: 100%;
        font-size: 20px; /* sizing this to the dynamic height of img will be a challenge */
        top: 20%;
    }
    

    And get what you want (with text now) as shown here. As noted, adding the text, the biggest challenge you are going to face is sizing that text. You will probably need to use javascript or an @media set to change text sizing with height. Personally, unless the text is vital (which I would think if this is background, it is not), I'd put the text in the image so that it scales with the size and stays right in relation to the image.

提交回复
热议问题