css中calc()的应用

栏目: CSS · 发布时间: 7年前

  • 假设要实现以下功能,随着视图的变化,图片始终保持如图的比列,放大或缩小
  • css中calc()的应用
  • 图片动态演示
  • css中calc()的应用

实现

  1. 抽象一下如图所示
  • css中calc()的应用
  • aw:宽高比宽度
  • ah:宽高比高度
  • w1:大图像的宽度
  • h1:大图像的高度
  • w2:小图像的宽度
  • h2: 小图像的高度
  • m:图像之间的边距
  1. 结合图可以得到如下表达式
  • w1 + m + w2 = 100%
  • 2 × h2 + m = h1
  • w1 / aw × ah = h1
  • w2 / aw × ah = h2
  • 现在开始求解决w1(然后是w2)。开始在公式2)中分别用公式3)和4)代替h1和h2,然后求解为w2如图所示:
  • css中calc()的应用
  • 然后,我可以在公式1)中用w2的结果替换它,并为w1求解:
  • css中calc()的应用
  • 用红色圈出的结尾处的表达式。它只包含边距,宽高比宽度和宽高比高度 - 在运行时都不会改变。因此,它是我们可以在构建时预先计算的常数值。为方便起见,我将此命名为常量值c:
c = (m × aw) / (ah × 3)

w1 = 2/3 × (100% − m) + c
w2 = 1/3 × (100% − m) − c
复制代码

代码

<!--html-->
<div class="thumbnails">
  <img src="https://placeimg.com/400/300/animals" alt="A randomly selected animal photo">
  <img src="https://placeimg.com/400/300/nature" alt="A randomly selected nature photo">
  <img src="https://placeimg.com/400/300/arch" alt="A randomly selected archirecture photo">
</div>

<!--scss-->
// Using values from the original design
$margin: 20px;
$aspect-width: 4;
$aspect-height: 3;
// Calculate c
$constant: ($margin * $aspect-width) / ($aspect-height * 3);


.thumbnails {
  width: 50%;
  margin: 0 auto;
  padding: $margin;
  border: 2px solid black;
  overflow: hidden; // crude clearfix
  
  
  // First image becomes big one on left
  > *:first-child {
    display: block;
    float: left;
    margin-right: $margin;

    // Magic formula!
    width: calc( (2 / 3 * (100% - #{$margin}) ) + #{$constant} );
  }

  // 2nd & 3rd images become smaller ones
  // on right
  > *:nth-child(n + 2) {
    display: block;
    float: right;

    // Magic formula!
    width: calc( (1 / 3 * (100% - #{$margin}) ) - #{$constant} );
  }

  // 3rd image also has top margin
  > *:nth-child(3) {
    margin-top: $margin;
  }
}
复制代码

参考链接


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Java和Android开发学习指南(第二版)

Java和Android开发学习指南(第二版)

Budi Kurniawan / 李强 / 人民邮电出版社 / 2016-3 / 69.00元

本书是Java语言学习指南,特别针对使用Java进行Android应用程序开发展开了详细介绍。 全书共50章,分为两大部分。第1部分(第1章到第22章)主要介绍Java语言基础知识及其功能特性。第2部分(第23章到第50章)主要介绍如何有效地构建Android应用程序。 本书适合任何想要学习Java语言的读者阅读,特别适合想要成为Android应用程序开发人员的读者学习参考。一起来看看 《Java和Android开发学习指南(第二版)》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试