2016-05-01 22 views
1

我有一个包含div内的方形图像,并希望包含div具有与图像相同的尺寸。图像的大小各不相同,因此未预先知道。特别要注意的是,图像是div内唯一的东西(好吧,不是严格意义上的,但其他元素是绝对定位的,因此基本上可以忽略)。保留一个包含div的图像大小

我目前拥有的代码如下:

div.container, image { 
    display: block; 

    /* ensure enough room for other content in sidebar */ 
    max-height: calc((100vh - 12em)/2); 

    /* don't allow image to escape sidebar boundaries */ 
    max-width: 256px; 

    /* forces image to be square as it's originally square */ 
    width: auto; 
    height: auto; 
} 

div.container { 
    position: relative; 
    margin: 1em auto; 
} 

我已经看到了有关使用padding-bottom一些帖子;虽然这确实使得包含的div为正方形,但它不一定与图像的大小相同,因为图像的高度可能会被迫远小于div的高度。

有没有干净的解决方案呢?

+0

你试过jQuery吗? –

+0

我宁愿不使用Javascript,除非在CSS中没有办法做到这一点。 –

+1

我认为你不能使用display:inline-block或浮动它吗? – wizzardmr42

回答

0

.container元素的display属性设置为inline-block而不是block

0

我能想到的最佳解决方案是父容器的display:table和图像包装器的display:table-cell

下面是一个容器的简单示例,它具有与所容纳图像相同的尺寸。

(该容器是用虚线边框)

* { 
 
    -moz-box-sizing: border-box; 
 
    -webkit-box-sizing: border-box; 
 
    box-sizing: border-box; 
 
} 
 

 
body { 
 
    padding: 10px; 
 
} 
 

 
img { 
 
    height: auto; 
 
    vertical-align:top; 
 
} 
 
section{ 
 
    display:table; 
 
} 
 
.image{ 
 
    display:table-cell; 
 
    vertical-align:top; 
 
    outline:5px dotted red; 
 
}
<section> 
 
    
 
    <article class="image"> 
 
     <img src="http://www.politicalmetaphors.com/wp-content/uploads/2015/04/blog-shapes-square-windows.jpg" width="240" height="240" alt=""> 
 
    </article> 
 
    </section>

0

div.container { 
 
    display:table; 
 
}

+0

它是做什么的?它有什么帮助?你为什么不编辑你的代码片段更明显? – dakab

0

只是要分裂和不给其高度和着,并把里面的图像,分区会自动根据高度和宽度图像的尺寸。

相关问题