max-width:100%在td或者table-cell里渲染不符合预期小笔记

时间:2022-04-21
本文章向大家介绍max-width:100%在td或者table-cell里渲染不符合预期小笔记,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一直没太注意有这个坑,td或者table-cell的元素里,如果没有指定容器宽度,那么容器里的img标签max-width:100% 在IE7-11,以及firefox下会不理会max-width的限制,例如:

<!DOCTYPE html>
<html>
<head>
	<title>max-width:100%不兼容小笔记-练小习</title>
	<style>
		*{
			margin: 0;
			padding: 0;
			border:0;
		}
		.img-wrap{
			display: table;
			margin: 20px auto;
			width: 50%;
		}
		.img{
			display: table-cell;
			border: 1px solid #cedfea;
			padding: 10px;
		}
		.img img{
			max-width: 100%;
		}
	</style>
</head>
<body>
<div class="img-wrap">
    <div class="img">
        <img class="smallcursor" src="https://mccdn.qcloud.com/static/img/f669eac6b6cd3d333cdf20256aa51eae/image.jpg">
    </div>
</div>
</body>
</html>

提示:你可以先修改部分代码再运行。

这个demo在IE7-11以及firefox下,img并没有被max控制。

解决的方式,给table设置table-layout: fixed,现在再看这个demo:

<!DOCTYPE html>
<html>
<head>
	<title>max-width:100%不兼容小笔记-练小习</title>
	<style>
		*{
			margin: 0;
			padding: 0;
			border:0;
		}
		.img-wrap{
			display: table;
			table-layout: fixed;
			margin: 20px auto;
			width: 50%;
		}
		.img{
			display: table-cell;
			border: 1px solid #cedfea;
			padding: 10px;
		}
		.img img{
			max-width: 100%;
		}
	</style>
</head>
<body>
<div class="img-wrap">
    <div class="img">
        <img class="smallcursor" src="https://mccdn.qcloud.com/static/img/f669eac6b6cd3d333cdf20256aa51eae/image.jpg">
    </div>
</div>
</body>
</html>

提示:你可以先修改部分代码再运行。

因为table-cell默认的automatic是内容决定宽度,IE和FF遵守了这一渲染方式,我们把他改成fixed,列宽由表格宽度和列宽度设定就好了。