CSS调整图像大小以适合容器

时间:2016-01-21 07:32:19

标签: html css

我希望将图像放入具有不同图像大小的容器中,如下所示:

示例:

1。尺寸较大的容器中的全尺寸。

2。中间位于水平尺寸的容器中。

第3。在具有垂直尺寸的容器中间。

查看此link

中的示例

4 个答案:

答案 0 :(得分:2)

正如Gautam所说,你需要使用

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

所以你可以为容器定义一个类

.container
{
    display:flex;
    align-items:center;
    justify-content:center;
    border:1px solid black;
    background-color: #ffffff;
    width: 50px;
    height: 50px;
}

一个图像类

.maxsize
{
    max-height:100%;
    max-width: 100%;
}

display:flex;属性使容器更易于配置,因此您可以更快地集中内容。您可以删除border属性,只是为了便于查看容器边缘。 希望它有所帮助。

Updated jsfiddle

答案 1 :(得分:1)

只需在父容器上设置此属性即可。

background-size : contain;
background-repeat: no-repeat;

这告诉浏览器确保图像不超过父容器的大小。

答案 2 :(得分:1)

这很容易做到

将图片与中心对齐

使用 max-height:100%max-width:100%

答案 3 :(得分:0)

罗伯特提到:

background-size : contain;
background-repeat: no-repeat;

但请务必添加:

background-position: center;

然后它将保持在容器的边界内并居中。

相关问题