如何更改CSS中指定的图像的宽度和高度

时间:2017-07-20 21:23:54

标签: javascript jquery html css

我正在尝试创建一个宽度为50%且高度为540px的div。我将background-repeat设置为no-repeat,但问题是图像没有覆盖“image-placeholder”

我对JQuery和Javascript的建议持开放态度。

li {
  float: right;
  margin: 10px;
  font-size: 150%;
  list-style: none;
}

ul {
  margin-right: 30px;
}

a {
  text-decoration: none;
  color: gray;
}

a:hover {
  color: lightgray;
}

#topnavbar {
  width: 100%;
  height: 37px;
  border-bottom: 1px lightgray solid;
}

#logotext {
  position: absolute;
  margin-top: -2px;
  font-size: 24px;
  color: rgb(24, 72, 150);
  cursor: default;
  font-weight: bold;
}

input {
  border: none;
  background-color: transparent;
  margin-top: 40px;
  padding-bottom: 500px;
  margin-top: 35px;
}

div#content:first-child {
  background-image: url(https://www.sitebuilderreport.com/assets/facebook-stock-up-446fff24fb11820517c520c4a5a4c032.jpg);
  background-repeat: no-repeat;
  width: 50%;
  height: 540px;
  display: block;
  background-color: green;
  margin-top: 30px;
  border: 3px black solid;
}

#content2 {
  background-image: url(https://www.stockvault.net/blog/wp-content/uploads/2017/06/summer-stock-photos-320x216.jpg);
  background-repeat: no-repeat;
  width: 50%;
  height: 540px;
  display: block;
  background-color: green;
  margin-top: 30px;
  border: 3px black solid;
}

#content3 {
  background-image: url(https://static.pexels.com/photos/33045/lion-wild-africa-african.jpg);
  background-repeat: no-repeat;
  width: 50%;
  height: 540px;
  display: block;
  background-color: green;
  margin-top: 30px;
  border: 3px black solid;
}

#logo {
  width: 10%;
  margin-top: -34px;
}
<div id="topnavbar">
  <p id="logotext"><img id="logo" src="logo.png"></p>
  <ul id="ullist">
    <li><a href="#">Settings</a></li>
    <li><a href="#">Account</a></li>
    <li><a href="#">Home</a></li>
  </ul>
</div>
<center>
  <div id="content"></div><br>
  <div id="content2"></div><br>
  <div id="content3"></div><br>
  <div id="content4"></div><br>
  <div id="content5"></div>
</center>

2 个答案:

答案 0 :(得分:3)

不使用Javascript,您可以使用CSS属性background-size设置为'cover'。 它将重新缩放背景图像以覆盖整个容器区域。它将节省图片的宽高比。部分图像可以溢出容器外 - 这是使用此解决方案的一个缺点。

background-size: cover;

https://jsfiddle.net/c59c1pja/

如果您不关心图像宽高比,可以使用

background-size: 100% 100%;

将图像转换为容器的尺寸

https://jsfiddle.net/6bpddoym/

答案 1 :(得分:0)

除了使用cover作为@Lukasz时,将background-repeat更改为round可以帮助您进行一些延伸。

  /* snip */
  background-repeat: round;
  background-size: cover;

https://jsfiddle.net/wahwahwah/5t3dsjna/15/