Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
716 views
in Technique[技术] by (71.8m points)

css - Vertically center image on page and maintain aspect ratio on resize

I am trying to do the following...

  1. Have an image that will always be horizontally and vertically centered on a page, whatever the screen size.
  2. Maintain aspect ratio on resize
  3. Have some text that will always be at the bottom of the viewport.

I have come up with two half solutions so far...

I am looking for a solution that combines both the above. Here is my code if you can't click the links above...

HTML

<div class="image">
  <div class="wrap">
    <img src="http://upload.wikimedia.org/wikipedia/commons/3/36/Hopetoun_falls.jpg">
 </div>
</div>
<div class="text">Scroll down</div>

CSS

//Solution 1

html, body {height: 100%}

body {
    position: relative;
    padding: 0;
    margin:0;
    font-family: sans-serif;
}
.image {
    position: relative;
    left: 0px;      
    height: 100%;
    background-position: 50% 50%;
    background-size: cover;
    background-attachment: scroll;
    text-align: center;
}
img {
  width: 70%;
  height: 70%;
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
}

.text {
    margin-top: -50px;
    text-align: center;     
}

// Solution 2 - same as above but with .wrap class

.wrap {
    overflow: hidden;
    position: relative;
    padding-top: 65%;
}

Any help would be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the image is big enough, you can use max-width and max-height instead of width and height. This will reduce the size of the image as necessary, maintaining the aspect ratio.

img {
    max-width: 70%;
    max-height: 70%;
}

To center it, you can use the absolute centering technique...

.wrap {
    position: relative;
}
img {
    margin: auto;
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
}

html, body, .image, .wrap {
  height: 100%;
  padding: 0;
  margin: 0;
}
.wrap {
  position: relative;
}
img {
  max-width: 70%;
  max-height: 70%;
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
}
.text {
  margin-top: -50px;
  text-align: center;
}
<div class="image">
  <div class="wrap">
    <img src="http://upload.wikimedia.org/wikipedia/commons/3/36/Hopetoun_falls.jpg">
  </div>
</div>
<div class="text">Scroll down</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...