【问题标题】:Using overflow hidden while aligning the contents the bottom right of a div?在将内容对齐div的右下角时使用隐藏溢出?
【发布时间】:2018-12-05 12:50:31
【问题描述】:
我有一个 200 像素宽 x 150 像素高的 div。 div 中的图像会更大。我想将内部图像与右下角对齐,同时在图像的其余部分使用溢出隐藏设置。所以只有图像的右下角应该是可见的。
我不知道在这种情况下如何使用相对定位,因为 div 中会有不同大小的图像。无论大小如何,我都需要 div 中的任何图像自动锁定右下角对齐。这可能吗?
这是我的代码:
<div align="right" valign="bottom" style="width:200px; height:105px; border: 1px dotted black; overflow: hidden;">
<div style="position:relative; bottom:0px; right:0px;">
<img src="https://www.catster.com/wp-content/uploads/2017/08/A-fluffy-cat-looking-funny-surprised-or-concerned.jpg" width="300" height="300" />
</div>
</div>
例如,我将图像设置为 500x300px,但在成品中,这将拉入不同的图像。
【问题讨论】:
标签:
html
css
overflow
positioning
【解决方案1】:
你不能使用相对于图像的位置来做到这一点。
但您可以同时使用relative 和absolute。
如果父级有position: relative,子级有position: absolute,则子级将使用父级的区域作为自我定位的限制
试试这个:
<div align="right" valign="bottom" style="width:200px; height:105px; border: 1px dotted black; overflow: hidden; position: relative">
<div style="position:absolute; bottom:0px; right:0px;" >
<img src="https://www.catster.com/wp-content/uploads/2017/08/A-fluffy-cat-looking-funny-surprised-or-concerned.jpg" width="300" height="300"/>
</div>
</div>
【解决方案2】:
为了相对于其父元素定位元素,您需要首先在父容器上设置position: relative。
HTML 文件:
<div class="outer">
<div class="inner">
<img src="https://www.catster.com/wp-content/uploads/2017/08/A-fluffy-cat-looking-funny-surprised-or-concerned.jpg" width="300"
height="300" />
</div>
</div>
CSS 文件:
.outer {
width: 200px;
height: 105px;
border: 1px dotted black;
overflow: hidden;
position: relative;
}
.inner {
position: absolute;
bottom: 0px;
right: 0px;
}
我提供了一个JSFiddle 来帮助您。
希望有帮助!