在不知道img大小的情况下,仅显示img的中心(水平和垂直)部分

时间:2013-12-03 09:08:42

标签: html css

我尝试了许多诸如table-cell之类的东西,但都没有。

我想要的只是<img src="" />标记中的<a>

A具有给定的宽度,高度和溢出:隐藏;

现在如何在不知道图像尺寸的情况下只显示img的中心部分?

Here is a fiddle这就是我得到的代码:

<a href="">
    <img class="center" src="http://images2.fanpop.com/images/photos/7000000/Nature-Around-the-World-national-geographic-7018209-1440-900.jpg" />
</a>
<a href="">
    <img class="center" src="http://naturalgeographic.net/wp/wp-content/uploads/2013/05/rock-climbing.jpg" />
</a>


<style type="text/css">
    a {
        position:relative;
        display:inline-block;
        width:300px;
        height:300px;
        overflow:hidden;
        border:solid 5px orange;
    }
    img.center {
        position:absolute;
        display:inline-block;
        top:-50%;
        left:-50%;
    }
</style>

如果只有那些元素不可能,我可以添加任何需要的东西。但是想要一个没有javascript的html / css解决方案。

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

我建议使用背景图片而不是img标签。这样,您可以通过以下方式仅显示图像的中心部分:

background:url('http://naturalgeographic.net/wp/wp-content/uploads/2013/05/rock-climbing.jpg') no-repeat center center;

Here是脏更新的JSFiddle。

答案 1 :(得分:0)

你需要操纵img宽度和高度,没有它你将无法将图片相对于它的父容器。像这样:

position: absolute;
display: inline-block;
top: -50%; left: -50%;  
width: 200%; height: 200%;

这是你的小提琴:http://jsfiddle.net/9JmQe/