inline-block的宽度不随图片的宽度变化

代码:

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    *{margin:0;padding: 0;}
    html, body {height: 100%;overflow: hidden;}
    .root {height: 100%;}
    .root-header,.root-footer {height: 20%;font-size: 30px;line-height: 2;text-align: center;background-color: #aaa;}
    .root-main {height: 60%;text-align:center;background-color: #92BDD2;}
    .tip {position: absolute;left: 0;top: 25%;font-size: 24px;text-align: left;}


    /*主要部分*/
    .img-box {
        position: relative;
        top: 15%;
        z-index: 2;
        display:inline-block; 
        _zoom:1;
        *display:inline;
        height: 70%; 
        background-color: #f00;
    }
    img { height: 100%; *height: 70%; }
    .img-box:hover .shadow{ display: block; }
    .shadow {
        display: none;
        position: absolute;
        left: 10px;
        top: 10px;
        height: 100%;
        width: 100%;
        background-color: #333;
        z-index: -1;
    }
    </style>
</head>
<body>
<div class="root">    
    <div class="root-header">header: height = 20%</div>
    <p class="tip">main: height = 60%<br>img-box: height = 70% <br> img: height = 100%; width = auto</p>


    <div class="root-main">
        <div class="img-box">
            <img src="./avatar.jpg" alt="">
            <!-- img-box 出现的阴影,不用 box-shadow 实现 -->
            <div class="shadow"></div>
        </div>
    </div>


    <div class="root-footer">footer: height = 20%</div>
</div>
</body>
</html>

效果

在线演示(已更新 2017/8/19):http://jsrun.net/dxYKp/edit

整个网页铺满浏览器,不能超出,并且图片的高度为浏览器高度的固定百分比,图片宽度随高度变化,然后在鼠标滑过图片是要出现阴影(要兼容IE8所以没用box-shadow实现阴影)

clipboard.png
图片描述

BUG:

以上代码,在改变浏览器大小的时候,img-box的高度改变,img高度等于img-box的高度,但是img-box的宽度不会改变,只能保持再页面一开始加载时候的大小,即使img的宽度变大超出或者缩小。
图片:

1、浏览器较大时初始化:

图片描述

浏览器变小:

图片描述


2、浏览器较小时初始化:

图片描述

浏览器变大

图片描述

暂时解决方案:

目前使用在改变浏览器大小的时候改变img-box的大小或者padding、margin等方式

window.onresize = function() {
 // 改变img-box 的margi、padding等都可以
  img.parentNode.style.width = getStyle(img).width;
};

问题:

请问这种现象是否是回流的问题?
请解释一下这种现象的原理?
请问是否有更好的解决方案?

环境

win10
chrome 55
IE 8 - 11

firefox是正常的
IE7(inline-block实现不一样)也是正常的

具体效果请看在线演示
请各位大神多多指教,谢谢。

阅读 4.8k
6 个回答

楼主所描述的问题还是挺详细的
不过按照我的开发经验和规范我没有这样写过。

现在可以省略div的闭合标签了?

你的bug是在哪款浏览器下,测试的。你要的浏览器大小改变时,这种效果,还是鼠标移上效果啊。你的height写很奇怪。

高度用 vh,不设置图片宽度

O__O "…,ios系统chrom浏览器。好像没问题。
楼主是在啥浏览器测试的?

占坑看有没有能够解答?
从来没见过这样的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题