如何使图像覆盖div的大小,同时保持纵横比,以便我仍然可以完整地看到图像?

问题描述 投票:0回答:1

我试图为我的页面的主要部分创建一个背景。图像的大小是640 x 480,我希望它是1204 x 184的容器的背景。我知道之前已经问过这个问题,但没有一个答案适合我。

问题:如何使图像覆盖div的大小,同时保持纵横比,以便我仍然可以完整地看到图像?

p.s我添加了我的代码,但我还没有足够的分数来添加图片到我的帖子。

*{
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}
.main-container{
    width: 98%;
    margin: auto;
    background: lightgray;
}

header{
    width:80%;
    height: 10%;
    background: grey;
    margin: auto
}
main{
    margin-top: 0px;
    width: 80%;
    height:600px;
    margin: auto;
    margin-top: 10px;
    background: url(https://placeimg.com/640/480/tech);
    background-size: 100%;
    background-position: center;
    background-repeat: no-repeat;
   
 }
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="main.css">
    <title>Layout practice</title>
</head>
<body>
   <div class="main-container">
       <header>
           <div class="main-header">
               <h1>Header</h1>
           </div>

       </header>

       <main>
           <!-- <div class="main-content">
                -->

       </main>

    <section class="lower-sec">
        <div class="left-box">

        </div>

        <div class="right-box">

        </div>

    </section>

    
   </div>
    
</body>
</html>
html css image background-image aspect-ratio
1个回答
0
投票

而不是使用background-size: 100%

background-size: contain;

参考:https://developer.mozilla.org/en-US/docs/Web/CSS/background-size

© www.soinside.com 2019 - 2024. All rights reserved.