How to make background image cover entire screen and ignore aspect ratio in CSS [duplicate]

女生的网名这么多〃 提交于 2021-02-10 18:13:14

问题


The background-size: cover property makes the image take the entire screen but it maintains the aspect ratio so only a portion of the image is seen on bigger screens. How can I make it ignore aspect ratio so that the image takes up the entire screen AND the entire image is visible?

HTML:

<html>
<head>


<link href="styles.css" rel=stylesheet>

 <title>
 Enjoy ;)
 </title>
</head> <script type="text/javascript" src="getBG.js"></script></head>
 <body>

    <div class="intro">
        <div class="textbg">
    <div class="introText">
     Welcome to PicShare
     </div>

     <div class="introDesc">
        Today's theme is 
     </div>
     </div>
    </div>



<div class="back"> </div>

<div class="bg1" onclick="genBg()"><script>genBg()</script></div>




 </body>

</html>

CSS:

html{
margin: 0px;
height: 100%;
}

body{
height: 100%;
margin: 0px;
background-color: #424242;

}

.intro{           //want this background to take up entire screen 
    height:100%;
    background-color: #424242;
    background-image: url("assets/themes/theme1.jpg"); 
    background-repeat: no-repeat;
    background-size:  cover;
    }

回答1:


You do that with background-size: 100% 100%, which means 100% of the width and height of the background area respectively.




回答2:


You have the option to set the background-size property to the following:

  • cover
  • percentages or pixels (#% #% / #px #px)
  • contain
  • etc

cover will allow you to scale the image to cover the entire body, while contain will only scale the image enough so that the full image is still visible.

HTML

<div id="a"></div>
<div id="b"></div>
<div id="c"></div>
<div id="d"></div>

CSS

div {
  margin-top: 12px;
  width: 400px;
  height: 50px;
  outline: 1px solid #000;
  background-image: url(http://i.magaimg.net/img/1h5k.png);
  background-position: center center;
  background-repeat: no-repeat;
}

#a {
  background-size: cover;
}
#b {
  background-size: 100% 100%;
}
#c {
  background-size: contain;
}
#d {
  /* Nothing */
}

https://jsfiddle.net/ef8cszhw/



来源:https://stackoverflow.com/questions/46454118/how-to-make-background-image-cover-entire-screen-and-ignore-aspect-ratio-in-css

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!