CSS3元素尺寸不能从百分比或自动转换为像素大小



我正在构建一个单页网站,在'开始屏幕'上显示80%屏幕宽度的矢量图形。一旦用户向下滚动,图形过渡到页面顶部的导航栏,高度为50px。从大尺寸到小尺寸的转换应该使用CSS3转换动画。

然而,当将元素从百分比或自动值缩放到固定像素值时,CSS转换似乎不起作用,反之亦然。我做了一个图表来展示这种效果。虽然div的高度可以很好地过渡,但宽度根本没有动画。

使用像素宽度作为图像的初始大小不是响应式设计的选择。代码:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        html, body{
            background-color: #010101;
            height: 100%;
        }
        .navbar--logo-item{
            background-color: #fff;
            height: 10px;
            width: 80%
            -moz-transition: all 0.5s ease-in-out;
            transition: all 0.5s ease-in-out;
        }
        .navbar--logo-item.small{
            height: 50px;
            width: 200px;
        }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('#toggle').click(function(){
                $('.navbar--logo-item').toggleClass('small');
            });
        });
    </script>
</head>
<body>
    <div class="navbar--logo-item"></div>
    <button id="toggle">
        Toggle Logo
    </button>
</body>
</html>

在现代浏览器中,可以使用calc来解决这个问题。

你可以转换一个计算值,只要它是齐次的。您的情况可以用如下的同构方式表示

.navbar--logo-item{
    width: calc(80% + 0px);
}
.navbar--logo-item.small{
    width: calc(0% + 200px);
}

请注意,这两个计算是相似的(它们是百分比和像素值的总和),但同时结果与您已经拥有的

相同。

小提琴另一种常见的方法是设置max-width为可能较大的原始值,比如

.navbar--logo-item{
    width: auto;
    max-width: 1000px; /* you don't need to set an accurate value */
}
.navbar--logo-item.small{
    max-width: 200px;   /* no need to set width */
}

如果你将logo的宽度设置为它的直接父元素的宽度,那么一切都是以像素为单位的,并且过渡将按照你想要的方式进行。

$(document).ready(function(){  
    var logo = $('.navbar--logo-item');
    
    function setWidthtoParent(target) {
        var parentWidth = target.parent().width();
        target.css('width', parentWidth);
    }
    
    setWidthtoParent(logo);
    
    $('#toggle').click(function(){
        logo.toggleClass('small');
    });
});
html, body{
  background-color: #010101;
  height: 100%;
}
.navbar--logo-item{
  background-color: #fff;
  height: 10px;
  -moz-transition: all 0.5s ease-in-out;
  transition: all 0.5s ease-in-out;
}
.navbar--logo-item.small{
  height: 50px;
  width: 200px !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
	<div class="navbar--logo-item"></div>
	<button id="toggle">
		Toggle Logo
	</button>
</body>

这并不理想,因为它需要添加一个!important声明来覆盖应用的内联样式。您还冒着在转换发生之前浏览器窗口被调整大小的风险。一个更好的解决方案是使用一致的单位(也许在SVG保持100%的同时转换父div的宽度,就像这样)。

最新更新