使用rem编写自适应屏幕网页造成div被span撑高的解决办法

原始代码:

<html>
<head>
    <meta charset="utf-8">
    <meta content="ie=edge" http-equiv="x-ua-compatible">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0" />
</head>    
<style type="text/css">
    #content{
        width:7.2rem
    }

    .price-div{
      background-color:yellow;
    }

    .price-div span{
      background-color:green;
    }    

    .price-unit{
        font-size:0.25rem;
    }

    .price-number{
        font-size:0.31rem;
    }
</style>
<body>
<div id="content" style="float:left">
    <div class="price-div" >
        <span class="price-unit"></span>
        <span  class="price-number">42</span>
    </div>
</div>

<script type="text/javascript">
    //计算字体大小
    var calculateFontSize = function () {
        var BASE_FONT_SIZE = 100;

        var docEl = document.documentElement,
                clientWidth = docEl.clientWidth;
        if (!clientWidth) return;
        docEl.style.fontSize = BASE_FONT_SIZE * (clientWidth / 720) + 'px';

    };
    calculateFontSize();

    // Abort if browser does not support addEventListener
    if (document.addEventListener) {
        var resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize';
        window.addEventListener(resizeEvt, calculateFontSize, false);
        document.addEventListener('DOMContentLoaded', calculateFontSize, false);
    }

</script>
</body>
</html>

 

效果:

 

原因:

rem缩放,导致,去掉缩放的js代码就好了。但这个不是解决办法。

 

解决方法一:

div设置高度并采用相对定位,span采用绝对定位。

<style type="text/css">
    #content{
        width:7.2rem
    }

    .price-div{
      background-color:yellow;
      height:0.4rem;
      line-height:0.4rem;
      position:relative;
    }

    .price-div span{
      background-color:green;
    }    

    .price-unit{
        font-size:0.25rem;
        position:absolute;
        top:0rem;
        left:0.2rem;
    }

    .price-number{
        font-size:0.31rem;
        position:absolute;
        top:0rem;
        left:0.5rem;
    }
</style>

效果:

 

解决方法二:

div设置高度,span等内联元素设置vertical-align为top。

<style type="text/css">
    #content{
        width:7.2rem
    }

    .price-div{
      background-color:yellow;
      height:0.4rem;
      line-height:0.4rem;
    }

    .price-div span{
      background-color:green;
    }    

    .price-unit{
        font-size:0.25rem;
        vertical-align:top;
    }

    .price-number{
        font-size:0.31rem;
        vertical-align:top;
    }
</style>

效果:

 

posted @ 2018-10-22 21:15  追极  阅读(1786)  评论(0编辑  收藏  举报