1

CSS中的calc()

 2 years ago
source link: https://jw1.dev/2018/12/04/a01.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

CSS中的calc()

作者: 一个球 发布时间: 2018-12-04 上次修改:2019-03-15 状态:已废弃

记得刚毕业的时候找工作面试前端,面试官问了我这样一个问题:

我现在需要一个搜索框,左边放input,右边放搜索按钮,搜索框固定120px,请你写一下布局。

当时我的内心:”太简单了!“。

于是我劈里啪啦敲了一堆:

<div class="demo_wrap"><input type="text" /><button>search</button></div>
.demo_wrap {
width: 600px;
margin: 0 auto;
}
.demo_wrap input {
width: 480px;
height: 40px;
}
.demo_wrap button {
width: 120px;
border: none;
height: 40px;
}

一个简单的搜索框就出来了,像这样:

然而面试官就是面试官,他又加了一个要求,我需要适配多种设备的分辨率

“切,看我 CSS 媒体查询一梭子!”

@media screen and (min-width: 1440px) {
}
@media screen and (min-width: 1366px) {
}
@media screen and (min-width: 1080px) {
}
@media screen and (min-width: 960px) {
}
@media screen and (min-width: 720px) {
}
/*...*/

面试官看了后还是摇头:“我要input随窗口大小变化而变化,而且button长度不变。”

怎么搞???

嗯,理所当然的,这家公司没有面试上。

calc(100% - 120px)

我要说的就是这个了。

改成这样之后,我的搜索框就变成了这样:

完整代码:

<div class="demo_wrap"><input type="text" /><button>search</button></div>
.demo_wrap {
width: 100%;
margin: 0 auto;
}
.demo_wrap input {
width: calc(100% - 120px);
height: 40px;
}
.demo_wrap button {
width: 120px;
border: none;
height: 40px;
}

可以试试改变浏览器的大小来验证是否真的达到了那位面试官的要求。

calc()会让你的 css 也拥有计算能力,支持+ 、- 、*、/四种运算符(小学啦)。这个属性的应用很简单,不过有几点要注意一下:

  1. 运算符左右一定要有空格,如果你写成100%-5px是不会工作的。
  2. calc不要拼错(废话
  3. 不要滥用calc(),能定实际数值就定实际数值,css 的运算速度肯定是没有 js 快的。

好了,今日份的 blahblah 结束!

有问题可以在下面评论或者发邮件给我,我都看得到,现在刚开始人少,只要是前端上的,我能解决的问题,一定会回复的!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK