无法将图片设置为适合整个div

时间:2019-09-26 10:46:59

标签: html css

我想为我的网站创建一些标题,但实际上我无法正确设置背景图片。我想从背景图片填充整个标题div,但实际上甚至不适合整个div。我该怎么办? (请不要怪我代码质量:D)

HTML

    <!DOCTYPE html>
    <html>
      <head>
      <link

 href="css.css" rel="stylesheet" type="text/css"/>
   </head>
    <body>
     <div class = "headerContainer">
      <div class = "headerCol1"><h1>LoremIpsum</h1></div>
      <div class = "headerCol2"><h1>LoremIpsum</h1></div>
      <div style = "clear:both;"/>
      <div class = "headerCol3"><h1>LoremIpsum</h1></div>
      <div style = "clear:both"/>
     </div>
  </body>
</html>

CSS

    body{
    background-color:#666766;
}

.headerContainer{

    height:100vh;
    border:solid 2px;
    background-image:url("https://i2.wp.com/oddshjelpen.com/wp-content/uploads/2018/08/350851-download-free-website-background-1920x1080-for-mobile-hd.jpg?ssl=1");
    background-size: contain;
  background-position: left-top;
  background-repeat:no-repeat;

}
.headerCol1{
    height:100px;
    width:600px;
    background-color:yellow;
    margin:0 auto;
}
.headerCol1 h1{
    text-align:center;
    font-size:40px;
    padding:15px;

    font-size:72px;
    letter-spacing:15px;

}

.headerCol2{
    height:70px;
    width:500px;
    background-color:yellow;
    margin-top:150px;
    float:right;
}

.headerCol2 h1{
    margin:0;
    padding:0;
    text-align:center;
    position:relative;
    top:50%;
    transform:translateY(-50%);
    font-size:62px;

}

.headerCol3{
    height:65px;
    width:550px;
    background-color:yellow;
    margin-top:20px;
    float:right;
}
.headerCol3 h1{
    margin:0;
    padding:0;
    text-align:center;
    position:relative;
    top:50%;
    transform:translateY(-50%);
    font-size:56px;
}

https://jsfiddle.net/48t7xLrg/

2 个答案:

答案 0 :(得分:1)

您必须将css下的background-size更新为cover更新。

.headerContainer {
    height: 100vh;
    border: solid 2px;
    background-image: url(https://i2.wp.com/oddshjelpen.com/wp-content/uploads/2018/08/350851-download-free-website-background-1920x1080-for-mobile-hd.jpg?ssl=1);
    background-size: cover;
    background-position: left-top;
    background-repeat: no-repeat;
}

Fiddle

答案 1 :(得分:0)

contain填满一个尺寸(全宽或全高),而cover填满图像直到两个尺寸都接触到侧面。

此外,也没有固定的高度值,因为在较小的屏幕上,您的子元素将位于标头之外。将height替换为min-height

.headerContainer{
  /* height:100vh; */
  min-height: 100vh;
  border:solid 2px;
  background-image:url("https://i2.wp.com/oddshjelpen.com/wp-content/uploads/2018/08/350851-download-free-website-background-1920x1080-for-mobile-hd.jpg?ssl=1");
  /* background-size: contain; */
  background-size: cover;
  background-position: left-top;
  background-repeat:no-repeat;
}