前端攻城狮

CSS3之calc()

2018-05-06  本文已影响1人  LemonnYan

一、calc()是什么

calc是英文单词calculate(计算)的缩写,是css3新增的功能,calc() 函数用于动态计算长度值。

语法:calc(数学表达式)

语法规则:

二、浏览器兼容性

浏览器兼容性:需要添加兼容性前缀

示例:

width:-moz-calc(40% - 1px); 
width:-webkit-calc(40% - 1px); 
width:calc(40% - 1px);

三、使用示例

示例1:手机端一屏显示

使用说明:
(1)html和body需要同时定义高度100%;
(2)头部和底部定高,中间部分使用calc相减;

示例效果图1:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>calc</title>
    <style>

        html, body {
            margin: 0;
            padding: 0;
            height: 100%;
            color: #ffffff;
            text-align: center
        }

        header {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100px;
            background-color: #1AA094
        }

        section {
            display: flex;
            align-items: center;
            justify-content: center;
            height: calc(100% - 100px - 150px);
            background-color: #4D5BB3
        }

        footer {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 150px;
            background-color: #A63DB8
        }

    </style>
</head>
<body>
    <header>
        这是header
    </header>

    <section>
        这是高度自动变化的区域
    </section>

    <footer>
        这是footer
    </footer>
</body>
</html>

示例2:九宫格
示例效果图12:


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>calc</title>
    <style type="text/css">
    * {
        margin: 0;
        padding: 0;
    }

    .grid-3 {
        width: calc(100%/3 - 5px);
        float: left;
        margin-right: calc(5px*3 /2);
        background: #eee;
        color: #333;
        height: auto;
        text-align: center;
        margin-bottom: calc(5px*3 /2);
        font-size: 18px;
        line-height: 100px;
    }

    .grid-3:nth-child(3n) {
        margin-right: 0;
    }
    </style>
</head>

<body>
    <div class="container">
        <div class="grid-3">1</div>
        <div class="grid-3">2</div>
        <div class="grid-3">3</div>
        <div class="grid-3">4</div>
        <div class="grid-3">5</div>
        <div class="grid-3">6</div>
        <div class="grid-3">7</div>
        <div class="grid-3">8</div>
        <div class="grid-3">9</div>
    </div>
</body>
</html>
上一篇下一篇

猜你喜欢

热点阅读