css - 将div设置为子图像的宽度和高度?

标签 css

JSFiddle

我有一个带有容器类的 div。此 div 的高度必须等于宽度。我通过以下方式实现了这一目标:

.container{
    background-color: #e6e6e6;
    position: relative;
}

.container:before{
    content: "";
    display: block;
    padding-top: 100%;
}

容器里面是一个图片容器,里面是一张图片。图像必须受到约束,它的高度或宽度不能超过容器并且仍然保持纵横比。这是通过以下方式实现的:

img{
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;

    max-height: 100%;  
    max-width: 100%; 
    width: auto;
    height: auto;

}

我的问题与图像支架有关,我需要它与其中的图像具有相同的宽度和高度。我怎样才能做到这一点?请仅使用 CSS。

最佳答案

https://jsfiddle.net/1tbrtoaj/4/

从您的 img 标签中删除 position: absolute。

.container{
    background-color: #e6e6e6;
    position: relative;
}

.container:before{
    content: "";
    display: block;
    padding-top: 100%;
}

.img-holder {
    border-style: solid;
    border-color: #0000ff;
}

img{
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;

    max-height: 100%;  
    max-width: 100%; 
    width: auto;
    height: auto;
}

关于css - 将div设置为子图像的宽度和高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29371522/

相关文章:

css - 对 Outlook 使用背景图像并居中,无间隙

jquery - 为什么我的响应式菜单在宽度调整大小/更改时没有显示?

css - 使用 SASS 或 CSS 变量时,rgba 效果不适用

css - Bourbon Neat 忽略媒体查询中的 'omega'

html - 为什么我的 HTML 表格不符合我的 CSS 列宽?

css - 为什么我的 Wordpress 主题在移动设备上丢失 CSS?

css - IE 条件语句仅适用于主页?

javascript - 如何使视口(viewport)跟随此 javascript 代码中的矩形?

css - 内容可编辑内联 div 为空时移动

css - 这个 CSS 是否被接受并且定义明确,或者是一个容易失败的 hack?