flexbox_切芥末酱迁移到Flexbox

flexbox

As front-end developers, the time has come to move away from using CSS floats and dive into the new and exciting world of flexbox. CSS floats are a dated approach to styling layouts; they have been available in Internet Explorer since version 4.0 and workarounds are required to make them malleable (including the clearfix hack and using the nth-child pseudo-class for wrapping columns).

作为前端开发人员,是时候摆脱使用CSS浮动控件,而进入Flexbox令人兴奋的新世界了。 CSS浮动是一种过时的布局样式方法。 自4.0版以来,它们已在Internet Explorer中提供,并且需要变通方法以使其具有延展性(包括clearfix hack使用nth-child伪类包装列)。

The main topic of this article is how to implement flexbox across multiple browsers considering its fragmentation. If you want to become more familiar with flexbox, there are many good resources available, and I highly recommend the following:

本文的主要主题是考虑到其分散性,如何在多个浏览器中实现flexbox。 如果您想对flexbox更加熟悉,可以使用很多不错的资源,我强烈建议以下内容:

By the end of this article, you should be able to:

在本文末尾,您应该能够:

  • Understand which versions of flexbox to target for a responsive website.

    了解响应式网站要定位的flexbox版本。
  • Utilise flexbox via feature detection (cutting the mustard) and provide a fallback for legacy browsers.

    通过功能检测(切芥末)来利用flexbox,并为旧版浏览器提供后备功能。
  • Move away from using IE conditional comments in most situations.

    在大多数情况下,不要使用IE条件注释。
  • Demonstrate a practical use for flexbox by creating a basic 2×2 grid with a legacy fallback.

    通过创建具有传统后备功能的基本2×2网格,展示Flexbox的实际用途。

Flexbox的简史 (A Brief History of Flexbox)

The Flexible Box Layout Module (a.k.a. flexbox) is a new way of structuring layouts in CSS. It has undergone multiple revisions and has evolved significantly in its relatively short existence. At the time of writing flexbox is still a W3C working draft, but, like other standards, that shouldn’t make it unappealing in a production environment.

灵活框布局模块 (又名flexbox)是CSS中布局布局的一种新方法。 它经过了多次修订,并且在其相对较短的时间内已经有了显着的发展。 在撰写本文时,flexbox仍是W3C的工作草案,但是,与其他标准一样,这不应使其在生产环境中不受欢迎。

There are three iterations of the standard, commonly referred to as the old syntax, the tweener syntax and the new syntax.

该标准有3种迭代,通常称为旧语法补间语法新语法

The limitations of flexbox are well documented:

flexbox局限性有据可查:

  • The old syntax does not support flex-wrap.

    旧的语法不支持flex-wrap

  • The tweener syntax is only supported in IE 10 (including mobile).

    仅IE 10(包括移动设备)支持tweener语法。
  • The new syntax is not fully implemented in Firefox (22-27) as it is missing the flex-wrap and flex-flow properties.

    由于缺少flex-wrapflex-flow属性,因此新语法尚未在Firefox(22-27)中完全实现。

Wrapping (flex-wrap) is an important feature of the specification, which is required to create a responsive grid. For this reason, it’s best to target only the tweener syntax and browser versions that fully implement the new syntax.

包装( flex-wrap )是该规范的重要功能,这是创建响应式网格所必需的。 因此,最好只针对补间语法和完全实现新语法的浏览器版本。

This leaves us with the following browser versions:

这为我们提供了以下浏览器版本:

  • Internet Explorer 10 (tweener syntax with the -ms- prefix)

    Internet Explorer 10(带有-ms-前缀的-ms-语法)

  • Internet Explorer 11 and Edge (new syntax)

    Internet Explorer 11和Edge(新语法)
  • Firefox 28+ (new syntax)

    Firefox 28+(新语法)
  • Chrome 21-28 (new syntax with the -webkit- prefix)

    Chrome 21-28(带有-webkit-前缀的新语法)

  • Chrome 29+ (new syntax)

    Chrome 29+(新语法)
  • Safari 6.1+ (new syntax with the -webkit- prefix)

    Safari 6.1+(带有-webkit-前缀的新语法)

  • iOS Safari 7.0+ (new syntax with the -webkit- prefix)

    iOS Safari 7.0+(带-webkit-前缀的新语法)

As there are browsers with a significant market share that do not support flexbox, these should fallback to using CSS floats. But how can this be expressed in code? What’s the best way to differentiate between browser versions that should receive CSS with floats instead of flexbox? What strategy can be used to ensure versions of Firefox that support the new syntax but don’t support wrapping are identified as legacy?

由于某些浏览器的市场份额很大,不支持flexbox,因此应回退到使用CSS float。 但是如何用代码表达呢? 区分应该使用浮点数而不是flexbox接收CSS的浏览器版本的最佳方法是什么? 可以使用什么策略来确保将支持新语法但不支持包装的Firefox版本识别为旧版?

Introducing: Cutting the mustard.

简介: 切芥末

切芥末(功能检测) (Cutting the Mustard (Feature Detection))

If you haven’t heard it as a technical term before, “Cutting the mustard” was coined by the development team at BBC News. The term stemmed from the fact that the BBC website must cater to a vast international audience and targeting browser versions and devices specifically would have been a cumbersome solution.

如果您以前从未听说过它是一个技术术语,那么“切芥末” 是BBC News的开发团队提出的 。 该词源于BBC网站必须迎合广大国际受众的事实,而专门针对浏览器版本和设备将是一个繁琐的解决方案。

The crux of the concept is identifying which browser/device/user agent is being used and serving polyfills to get the site to work. The existence of specific features is detected on the client side and therefore the most appropriate solution for the available technology is delivered.

这个概念的症结在于确定正在使用哪个浏览器/设备/用户代理,并提供polyfill来使站点正常工作。 在客户端检测到特定功能的存在,因此提供了适用技术的最合适解决方案。

Feature detection is not new. The aforementioned BBC article was published in March 2012 and while it has grown in popularity, it’s surprising to see websites still implementing IE-specific conditional classes as popularised by Paul Irish in 2008.

功能检测不是新功能。 前面提到的BBC文章发表于2012年3月,尽管它越来越流行,但令人惊讶的是,看到网站仍在实施IE特定的条件类 ,这是Paul Irish在2008年流行的。

Modernizr (contributed to by Paul Irish) is all about feature detection:

Modernizr (由Paul Irish贡献)完全涉及特征检测:

Taking advantage of cool new web technologies is great fun, until you have to support browsers that lag behind. Modernizr makes it easy for you to write conditional JavaScript and CSS to handle each situation, whether a browser supports a feature or not. It’s perfect for doing progressive enhancement easily.

在您必须支持落后的浏览器之前,充分利用酷炫的新Web技术非常有趣。 无论浏览器是否支持功能,Modernizr均可让您轻松编写条件JavaScript和CSS来处理每种情况。 非常适合轻松进行渐进增强。

Although CSS now has native feature detection, it currently does not have enough market share to be viable for real-world use. The remainder of this article will discuss how to ditch the IE conditional comments in favour of feature detection in JavaScript.

尽管CSS现在具有本机功能检测功能 ,但目前市场份额不足,无法在现实世界中使用。 本文的其余部分将讨论如何放弃IE条件注释以支持JavaScript中的特征检测。

识别功能和浏览器 (Identifying Features and Browsers)

Every project requires a different set of features in order to function. There are multiple ways feature detection can be realised, the easiest of which includes:

每个项目都需要一套不同的功能才能运行。 有多种方法可以实现特征检测,其中最简单的方法包括:

The most efficient approach is the vanilla JavaScript implementation. It’s fast (as it doesn’t require the client to download any additional libraries) and does not require any additional processing. This approach is far from perfect as there are known issues; however there are ways to overcome common feature detection problems.

最有效的方法是原始JavaScript实现。 它速度很快(因为它不需要客户端下载任何其他库),并且不需要任何其他处理。 由于存在已知问题,这种方法远非完美。 但是,有一些方法可以克服常见的特征检测问题

[B]rowser detection has become an impossible tangle, and has largely fallen out of use, to be superseded by something far better — feature detection.

[B]浏览器检测已成为一种不可能的纠结,并且在很大程度上已不再使用,而被功能更好的东西所取代。

[…] feature detection isn’t completely reliable either — there are times where it fails.

[…]功能检测也不完全可靠-有时会失败。

James Edwards

詹姆斯·爱德华兹

Choosing Modernizr for cutting the mustard may not be as efficient (as it requires downloading and client processing), but manually detecting flex-wrap support is not a straightforward task. It’s also important to note that although Modernizr version 2 doesn’t detect flex-wrap, version 3 does! The feature is labelled as Flex Line Wrapping.

选择Modernizr切芥末可能没有那么有效(因为它需要下载和客户端处理),但是手动检测flex-wrap支持并不是一件容易的事。 同样重要的是要注意,尽管Modernizr 2版没有检测到flex-wrap ,但3版却可以! 该功能标记为Flex Line Wrapping

Although the option exists to use the CSS classes attached to the document root produced by Modernizr (e.g.: html.flexwrap), it’s better to serve separate CSS files for each experience to reduce the download size of the site.

尽管存在使用由Modernizr生成的文档根目录附加CSS类的选项(例如: html.flexwrap ),但是最好为每种体验提供单独CSS文件以减小站点的下载大小。

The BBC News developers refer to two types of browsers:

BBC新闻开发人员指的是两种类型的浏览器:

Someone on the team started referring to them as “HTML4 browsers” and “HTML5 browsers”, which we find is easier to communicate the sentiment to non-technical people.

团队中的某人开始将它们称为“ HTML4浏览器”和“ HTML5浏览器”,我们发现它们更容易与非技术人员交流。

BBC Responsive News

英国广播公司响应新闻

This rationale was perfectly valid when you consider the climate of the browser landscape in 2012; however as new features become available, the division is not necessarily as clear. Flexbox, for example, isn’t fully supported in all “HTML5” browsers.

当您考虑2012年浏览器市场的气候时,这个理由是完全正确的; 但是,随着新功能的推出,划分并不一定那么清晰。 例如,并非所有“ HTML5”浏览器都完全支持Flexbox。

A robust approach is to differentiate between “legacy” and “modern” browser versions. In addition, some projects may require multiple divisions where half-way (or “transitional”) browsers can be identified.

一种可靠的方法是区分“传统”和“现代”浏览器版本。 另外,某些项目可能需要多个部门,以便可以识别中途(或“过渡”)浏览器。

实施方法 (Implementing the Approach)

Start by creating the following files:

首先创建以下文件:

  • index.html – the main HTML file

    index.html –主HTML文件

  • stylesheets/modern.css – styles for modern browsers (media queries, flexbox with wrapping)

    stylesheets/modern.css –现代浏览器的样式(媒体查询,带包装的flexbox)

  • stylesheets/legacy.css – styles for legacy browsers (no media queries, no flexbox)

    stylesheets/legacy.css –旧版浏览器的样式(无媒体查询,无flexbox)

  • scripts/dependencies.js – performs feature detection

    scripts/dependencies.js –执行功能检测

Here’s how our index.html file will look:

这是我们的index.html文件的外观:

<!DOCTYPE html>
<html class="no-js">
  <head>
    <title>Cutting the mustard</title>
    <script src="javascripts/dependencies.js"></script>
    <noscript>
    <link rel="stylesheet" href="stylesheets/legacy.css">
    </noscript>
    <!-- ... -->
  </head>
  <body>
    <div class="container">
      <div class="cell cell-1">Cell 1</div>
      <div class="cell cell-2">Cell 2</div>
      <div class="cell cell-3">Cell 3</div>
      <div class="cell cell-4">Cell 4</div>
    </div>
  </body>
</html>

Notice that there are no IE conditional comments? Just clean and valid HTML code. And if the browser does not have JavaScript enabled, it will fall back to using legacy.css regardless of its level of support.

请注意,没有IE条件注释? 只是干净有效HTML代码。 而且,如果浏览器未启用JavaScript,则无论支持级别如何,它都将退回到使用legacy.css

You may also notice that the script tags are at the top of the HTML page. This is because Modernizr should process and inject the stylesheets before the browser paints for the first time. This reduces repaint and helps to avoid a Flash Of Unstyled Content (FOUC). But remember that most script tags would be at the bottom of the page.

您可能还会注意到脚本标记位于HTML页面的顶部。 这是因为Modernizr应该在浏览器第一次绘制之前处理并注入样式表。 这减少了重新绘制,并有助于避免出现未样式化内容(FOUC)的闪烁 。 但是请记住,大多数脚本标签将位于页面底部。

Our legacy.css file will contain the following:

我们的legacy.css文件将包含以下内容:

.container {
}

/* clearfix */
.container:after {
  content: "";
  display: table;
  clear: both;
}

.cell {
  width: 50%;
  float: left;
}

/* wrapping */
.cell:nth-child(2n+1) {
  clear: left;
}

/* for visiblity */
.cell-1 { background-color: #000; color: #fff; }
.cell-2 { background-color: #666; color: #fff; }
.cell-3 { background-color: #ccc; color: #000; }
.cell-4 { background-color: #fff; color: #000; }

This implementation includes a clearfix hack and the :nth-child pseudo-class for wrapping. It works in most browsers; however Internet Explorer 8 requires Selectivizr or an equivalent solution to get the selector working.

此实现包括一个clearfix hack和用于包装的:nth-child伪类。 它适用于大多数浏览器; 但是,Internet Explorer 8需要Selectivizr或等效解决方案才能使选择器正常工作。

Next, our modern.css file:

接下来,我们的modern.css文件:

.container {
  /* Internet Explorer 10
   */
  display: -ms-flexbox;
  -ms-flex-wrap: wrap;

  /* Chrome 21-28
   * Safari 6.1+
   * Opera 15-16
   * iOS 7.0+
   */
  display: -webkit-flex;
  -webkit-flex-wrap: wrap;

  /* Chrome 29+
   * Firefox 28+
   * Internet Explorer 11+
   * Opera 12.1 & 17+
   * Android 4.4+
   */
  display: flex;
  flex-wrap: wrap;
}

.cell {
  -webkit-flex: 1 0 50%;
      -ms-flex: 1 0 50%;
          flex: 1 0 50%;
}

/* for visiblity */
.cell-1 { background-color: #000; color: #fff; }
.cell-2 { background-color: #666; color: #fff; }
.cell-3 { background-color: #ccc; color: #000; }
.cell-4 { background-color: #fff; color: #000; }

Don’t be put off by the size of this file. The comments make it appear larger, but these make it easier in development to understand what each section is targeting.

不要因为这个文件的大小而推迟。 注释使它看起来更大,但是这些注释使开发中更容易理解每​​个部分的目标。

Next we will write the code for dependencies.js.

接下来,我们将为dependencies.js编写代码。

As mentioned, we need to generate a version of Modernizr (version 3) which detects the support of the flex-wrap property. Include the code at the top of the JavaScript file.

如前所述,我们需要生成一个Modernizr版本(版本3),该版本可以检测对flex-wrap属性的支持 。 在JavaScript文件顶部包含代码。

/* Include Modernizr v3 with 'Flex line wrapping' here */

(function() {
  var isModern = Modernizr.flexwrap;

  var link = document.createElement('link');
  link.rel = 'stylesheet';
  link.type = 'text/css';
  link.href = 'stylesheets/' + (isModern ? 'modern' : 'legacy') + '.css';

  document.getElementsByTagName('head')[0].appendChild(link);
})();

You can optionally increase the requirements for a modern experience by adding to the isModern Boolean. For example:

您可以选择通过添加isModern布尔值来增加对现代体验的要求。 例如:

var isModern = Modernizr.flexwrap && 'querySelector' in document;

萨斯解决方案 (Sass Solutions)

You can use Sass to abstract your approach to implementing flexbox. This reduces the size of the CSS output and makes it easier to maintain:

您可以使用Sass抽象实现Flexbox的方法。 这样可以减小CSS输出的大小,并使维护更容易:

%flexbox {
  display: -ms-flexbox;
  -ms-flex-wrap: wrap;
  display: -webkit-flex;
  -webkit-flex-wrap: wrap;
  display: flex;
  flex-wrap: wrap;
}

.container1 {
  @extend %flexbox;
}

.container2 {
  @extend %flexbox;
}

渐进增强和浏览器测试 (Progressive Enhancement and Browser Testing)

It’s important to understand the differences between flexbox and CSS floats. Your implementation will not look exactly the same in each of the experiences — but the notion of progressive enhancement means that it doesn’t necessarily have to.

了解flexbox和CSS浮点数之间的区别很重要。 您的实现在每种体验中看起来都不完全相同,但是渐进增强的概念意味着不一定必须如此。

For example, by default, flexbox will stretch all cells on the same row to have the same height. Therefore, if one cell is 3 lines long and the adjacent row is 10 lines long, the background will stretch on both cells to 10 lines. The fallback for CSS floats will not do this and both cells will have uneven heights.

例如,默认情况下,flexbox会将同一行中的所有单元格拉伸为相同的高度。 因此,如果一个单元格长3行,而相邻行长10行,则背景将在两个单元格上延伸到10行。 CSS浮动的后备功能将无法做到这一点,并且两个单元的高度都将不均匀。

Testing the layout in multiple browsers is still a requirement, but remember that forcing the value of isModern to false in JavaScript can help test legacy solutions in any browser:

仍然需要在多个浏览器中测试布局,但是请记住,在JavaScript isModern的值强制isModern为false可以帮助在任何浏览器中测试遗留解决方案:

var isModern = false; // Modernizr.flexwrap;

结论 (Conclusion)

In this article, I’ve provided the basics for using feature detection to serve two different stylesheets on the same HTML code base. This is an extremely effective way of beginning the upgrade process away from CSS floats and reducing the dependency on IE conditional comments.

在本文中,我提供了使用功能检测在同一HTML代码库上提供两个不同样式表的基础。 这是从CSS浮动开始升级过程并减少对IE条件注释的依赖的极其有效的方法。

Although there has been a strong focus on detecting support for flexbox, it’s important to note that as new features are developed for browsers, this approach to cutting the mustard can be adapted and evolved to suit future requirements.

尽管一直非常关注检测对flexbox的支持,但需要注意的是,随着为浏览器开发了新功能,这种适应芥末的方法可以适应和发展以适应未来的需求。

Once Internet Explorer 10 falls out of popularity with the browser market share in your target sector, you may be able to ditch the tweener syntax and deliver leaner code solely through the use of the new syntax.

一旦Internet Explorer 10在目标领域中的浏览器市场份额中不再流行,您就可以放弃补间语法,而仅通过使用新语法来提供精简代码。

So now that you have all of the theory, why not get well acquainted with flexbox in your next project?

因此,既然您已经掌握了所有理论,那么为什么不在下一个项目中熟悉flexbox?

翻译自: https://www.sitepoint.com/migrating-flexbox-cutting-mustard/

flexbox

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值