我正在研究一个包含2个元素的div:图像和文本。图像占据div
的前半部分(顶部),文本占据div
(底部)的底部第二部分。
我希望图像适合div
的大小,但不要拉伸,并且还希望对每个元素应用不同的悬停效果。我一直在努力,但我没有建立这种结构。这就是我到目前为止所做的:
.work-item {
position:relative;
height:300px;
width:350px;
}
.work-item-image {
position:absolute;
top:0;
}
.work-item-image img {
max-height: 150px;
max-width: 350px;
object-fit: cover;
}
.work-item-text {
position:absolute;
vertical-align:middle;
max-height: 150px;
max-width: 350px;
}
<div class="work-item">
<a href="#">
<div class="work-item-image">
<img src="..."/>
</div>
<div class="work-item-text">
<h1>Hello Worl</h1>
</div>
</a>
</div>
答案 0 :(得分:2)
不要固定图像的宽度。每个div的宽度必须相等。此代码可能对您有所帮助。使用Photoshop等调整图像大小
.work-item {
position:relative;
height:300px;
width:350px; or width: 100%;
}
.work-item-image {
position:absolute;
top:0;
}
.work-item-image img {
max-height: 150px;
object-fit: cover;
}
.work-item-text {
position:absolute;
vertical-align:middle;
max-height: 150px;
width: 350px; or width: 100%;
}
答案 1 :(得分:0)
将此css用于.work-item-image
.work-item-image {
float: right;
width: 100%;
}
答案 2 :(得分:0)
只需使用display: inline-block
代替绝对位置,就像这样:
.work-item {
position:relative;
height:300px;
width:350px;
}
.work-item-image {
display: inline-block;
}
.work-item-image img {
max-height: 150px;
max-width: 350px;
object-fit: cover;
}
.work-item-text {
display: inline-block;
max-height: 150px;
max-width: 350px;
}
<div class="work-item">
<a href="#">
<div class="work-item-image">
<img src="..."/>
</div>
<div class="work-item-text">
<h1>Hello Worl</h1>
</div>
</a>
</div>
答案 3 :(得分:0)
试试这个。尝试找到其他解决方案,然后绝对。 CSS:
.work-item {
height:300px;
width:350px;
}
.work-item-image {
top:0;
}
.work-item-image img {
max-height: 150px;
max-width: 350px;
object-fit: cover;
}
.work-item-text {
margin: 0 auto;
vertical-align:middle;
max-height: 150px;
max-width: 350px;
}
h1 {
text-align: center;
}
img {
display: block;
max-width: 100%;
height: auto;
margin: 0 auto;
}
HTML:
<div class="work-item">
<a href="#">
<div class="work-item-image">
<img src="..."/>
</div>
<div class="work-item-text">
<h1>Hello Worl</h1>
</div>
</a>
</div>