图像高度匹配容器

时间:2018-04-05 14:15:35

标签: html css

如何使图像始终在容器内完全包含完全相同的高度和宽度?

.container {
  width: 500px!important;
  height: 800px!important;
}

.container:before {
  content: "";
  background: rgba(0, 0, 0, 0.2);
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  position: absolute;
  width: 500px;
  height: 800px;
}

.content_holder {
  position: absolute;
  bottom: 0;
  padding: 5%;
}

.custom_container .content_holder h3 {
  color: #fff!important;
}

.custom_container .content_holder p {
  color: #fff!important;
}
<div class="container">
  <img src="http://wrighthand.uk.w3pcloud.com/wp-content/uploads/2018/03/shutterstock_1016869756.jpg" />
  <div class="content_holder">
    <p>Subject</p>
    <h3>Container Title</h3>
    <a class="button">Learn more</a>
  </div>
</div>

由于某种原因,图像不会像我试图将其添加到的网站上那样放在容器中。

http://wrighthand.uk.w3pcloud.com

2 个答案:

答案 0 :(得分:0)

试试这个:

&#13;
&#13;
.container {
  width: 500px!important;
  height: 800px!important;
}

.container:before {
	content: "";
	background: rgba(0,0,0,0.2);
	top: 0;
	left: 0;
	bottom: 0;
	right: 0;
	position: absolute;
  width: 500px;
  height: 800px;
}

.content_holder {
	position: absolute;
	bottom: 0;
	padding: 5%;
}

.custom_container .content_holder h3 {
	color:#fff!important;
}

.custom_container .content_holder p {
	color:#fff!important;
}
&#13;
<div class="container">
<img src="http://wrighthand.uk.w3pcloud.com/wp-content/uploads/2018/03/shutterstock_1016869756.jpg" width="100%" height="100%"/>
<div class="content_holder">
<p>Subject</p>
<h3>Container Title</h3>
<a class="button">Learn more</a>
</div>
</div>
&#13;
&#13;
&#13;

它现在非常适合。 (它有点扭曲,但是......)

答案 1 :(得分:0)

您可以将图片作为容器的background,然后使用背景定位属性,例如,

  background-image: url('http://wrighthand.uk.w3pcloud.com/wp-content/uploads/2018/03/shutterstock_1016869756.jpg');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;

.container {
  width: 500px;
  height: 800px;
  background-image: url('http://wrighthand.uk.w3pcloud.com/wp-content/uploads/2018/03/shutterstock_1016869756.jpg');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  position: relative;
}

.container:before {
  content: "";
  background: rgba(0, 0, 0, 0.2);
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  position: absolute;
}

.content_holder {
  position: absolute;
  bottom: 0;
  padding: 5%;
  color: #fff;
}

a {
  color: inherit;
}
<div class="container">
  <div class="content_holder">
    <p>Subject</p>
    <h3>Container Title</h3>
    <a class="button">Learn more</a>
  </div>
</div>