- A Love Letter to CSS
- Originally written by TJ VanToll
- The Nuggets translation Project
- Translator: reid3290
- Proofreader: Changkun, CACppuccino
When I talk to colleagues about my growing love of CSS, they stare at me as if I’ve made an unfortunate life decision.
“TJ, sit over here and we’ll talk about how one bad choice you made as a child doomed you to failure for life.”
Sometimes I think developers — some of the most opinionated people on the planet — only agree on one thing: CSS is the worst.
Mocking CSS is one of the best ways to make people laugh at tech conferences, black CSS emojis have been flooded, I think not to put two in this are sorry everyone.
But today I’m going to wash your heads. I’m going to convince you that CSS is one of the best technologies you use on a daily basis. CSS is beautifully designed and you should be grateful every time you open a.css file!
My argument is fairly straightforward: it is very difficult to create a comprehensive style system for building complex user interfaces, and any alternative to CSS is only worse than CSS.
To illustrate my point, I’ll compare CSS to several other style systems, starting with an older technique.
Oh, my God, remember Java Applets?
In college, I wrote some applications using Java Applets, a technology that is now almost obsolete. Java appltes are basically Java applications that you can embed arbitrarily in your browser using the
A simple Java applet that takes you back to the late 90’s
Java Applets were introduced in 1995 and have grown in popularity over the years. If you were out in the late ’90s, you remember the technology debate between Web technologies and Java Applets.
Like most technologies for building user interfaces, Java Applets allow you to change the appearance of various controls on a user interface. And because Java Applets are seen as a legitimate alternative to Web development, the ease of laying out controls in Applets is sometimes compared to implementing the same functionality using Web technologies.
Java Applets certainly don’t use CSS, so how does it do UI layout? It’s not easy. A Google search for “change button color in Java applet” returns the first result code as follows:.
Import java.applet.applet; import java.applet; import java.applet. import java.awt.Button; import java.awt.Color; Public class ChangeButtonBackgroundExample extends the Applet {public void init () {/ / create a Button for the = new Button("Button 1"); Button button2 = new Button("Button 2"); /* * To change the button background Color, use the * setBackground(Color c) method. */ button1.setBackground(Color.red); button2.setBackground(Color.green); // Add (button1); add(button2); }}Copy the code
The first thing to note is that Java Applets don’t provide a way to separate code logic from style, just as you might use HTML and CSS on a web page. It will be the subject of the rest of this article.
Second, it takes a lot of code to create two buttons and change their background color. If you’re thinking, “Well, this approach is going to get out of hand pretty quickly when it comes to developing practical applications,” then you can begin to understand why Web technologies are finally trumped by Java Applets.
That being said, I know what you’re thinking.
“TJ, you haven’t completely convinced me that CSS has a better style system than Java applets. You should have set the bar higher.”
True, Java applets’ visual apis are not the gold standard for interface design, so let’s turn our attention to the current development: Android apps.
Why is style layout difficult for Android applications?
In some ways, Android is a modern, advanced version of Java Applets. Like Java Applets, Android uses Java as a development language. (However, according to Google’s recent announcement at Google I/O), you’ll soon be able to use Kotlin.) But unlike Java Applets, Android includes a set of conventions that make building user interfaces easier and more like building Web applications.
In Android applications, the definitions of interface controls are written in XML files, and the logic to interact with those controls is written in separate Java files. This is much like a Web application — HTML files are responsible for tag structure, and separate JavaScript files are responsible for behavioral logic.
The following code is a very simple Tag structure for an Android “activity” (which is basically a page) :
Copy the code
Copy the code
This can be a bit confusing for Web developers, but keep in mind that a basic “index.html” file has its quirks. You see here is two UI components, a < android. Support. The constraint. ConstraintLayout > and a < android. Widget. The Button >, each component has a variety of properties. For intuition, the above application works on an Android phone as shown below.
Back to the main idea of this article, how do you style these components? Similar to the Style property on the Web, basically every UI component on Android has a variety of properties that you can assign values to control the appearance of the component.
For example, if you want to change the background color of the buttons in the example above, you can use the Android: Background property. In the code below I apply this property to make the button background red.
Copy the code
Copy the code
So far so good. Android Studio, the Google-recommended Android development environment, even provides a powerful visual editor that makes it easy to configure some of these common properties. The image below shows a design view of the sample application in Android Studio. Note that you can easily configure properties such as background using the right pane of the screen.
It’s easy to apply some basic styles to Android interface controls with tools like design Attempt. But that’s where Android’s advantages end.
Actual application development requires much more than basic styles, and in my experience, dealing with complex styles is the dividing line between redundant Android code and concise CSS code. For example, suppose you want to create a collection of key-value pairs that are easy to reuse — similar to classes in CSS. You can do something similar in Android, but it gets messy pretty quickly.
Android applications have a styles.xml file in which you can create hierarchical BLOCKS of XML code. For example, if you want all buttons in your app to have a red background, you can create a “RedTheme” style using the following code:
<item name="android:buttonStyle">@style/RedButton</item>
<item name="android:background">#ff0000</item>
Copy the code
This way, you can apply the Android :theme=”@style/RedTheme” property to the corresponding top-level UI component. I applied this property to the top-level layout component in the example above, as shown in the code below.
Copy the code
This does what you want, and all the buttons in this layout component do turn red, but we can think back for a moment. Button {background: red; } can be done with a lot of XML code. And it’s only going to get more complicated as the application gets bigger.
In general, the slightly more complex styles in Android tend to involve nested XML configuration files or a lot of Java code for creating extensible components — neither of which is satisfying to me.
Let’s look at the animation. Android has some built-in animations that are nice and easy to use, but custom animations must be implemented in Java code. (Here’s an example.) There is no such thing as CSS animation in Android, and it is impossible to write the configuration management and application styles of animation together.
Let’s look at media queries. Android allows you to implement properties similar to CSS media queries and use them in UI components, but this is completely coupled to the tag structure and cannot be reused across pages or views.
To give you a better understanding of media queries in Android, here is a first code example of the various screen sizes supported by Android documentation. I’ve copied it as it is for comparison the next time you complain about CSS media queries.
Copy the code
Copy the code
We could have gone through all the features of CSS, but we can conclude from the examples above that it is possible to implement a variety of styling effects on Android, but it is always more complicated than it is on the Web.
It’s easy to talk about redundancy in Android XML, but it’s really hard to come up with a clear, concise UI component style mechanism that works well in large-scale applications. Subjectively you could certainly make examples of CSS as bad as the Android example above, but after working with both technologies, I would not hesitate to choose CSS.
For the sake of completeness, let’s talk about another platform that can render UI components: iOS.
Why is style layout difficult for iOS apps?
IOS is somewhat unique in the software development industry, as I know of the only software platform where UI development is primarily done through visual tools. That tool is called Storyboard, and use it in combination with Xcode to develop iOS and macOS applications.
To give you a better idea of what I’m talking about, the image below shows how to add two buttons to a view in an iOS app.
It’s worth noting that storyboards are not always necessary to develop iOS apps, but the alternative is to develop much of the user interface in Objective-C or Swift code, so Apple officially recommends storyboards for iOS development.
Note that Storyboard scenarios are beyond the scope of this article, but if you’re interested, check out the Quora discussion on this topic.
Back to the main idea of this article, how do you style UI components in iOS? As you might have guessed, it’s easy to configure the respective properties of UI controls in a visual editor. For example, if you want to change the background color of a button, you can easily do so using the menu on the right side of the screen.
Much like Android, it’s easy to configure various properties for artifacts. But again, like Android, things get trickier when requirements get complicated. For example, how do you make multiple buttons look the same in an iOS app? That’s not easy.
IOS has a concept of outlets, which is essentially a mechanism that allows Objective-C or Swift code to retrieve references to interface components. Think of outlets as document.getelementById () in iOS. To style multiple iOS UI components, you need to get an explicit reference or outlet that iterates through each control in the storyboard and assigns changes to it. The following example shows how the Swift view controller changes the background color of all buttons.
import UIKit class ViewController: UIViewController {// A collection of button outlets filled with data using Xcode's storyboard editor @ibOutlet var buttons: [UIButton]! Func styleButtons() {for button in self.buttons {// Give the view a red background button.backgroundcolor = by setting the backgroundColot property Uicolor. red}} // The entry point of the view controller, which iOS calls after the view is loaded. override func viewDidLoad() { super.viewDidLoad() self.styleButtons() } }Copy the code
The point here is not to go into specifics, so I won’t go into what each Swift line does. The point is that styling multiple controls inevitably involves Objective-C or Swift code, which in CSS can be done by defining a simple class name.
It’s not hard to imagine that more complex iOS style requirements would involve more code. For example, creating a simple iOS “theme” involves a bunch of UIAppearance APIs, while working with multiple device types requires learning the sophisticated Auto Layout.
To be fair, native developers can also point out some weird features in CSS, and to some extent they are right. After all, whether it’s the Web or native platforms such as iOS and Android, positioning, styling, animating, and dealing with compatibility across devices are no easy task. Any comprehensive style system inevitably makes trade-offs, but having worked in a variety of software industries, I think CSS stands out with a number of advantages.
Why is CSS better
CSS is very flexible
CSS allows you to separate your application’s concerns, so there is complete independence between style logic and application body logic. The principle of separation of concerns has been a fundamental principle of Web development for decades, and the architectural nature of CSS is one of the main factors that makes this principle practical.
That being said, the flexibility of CSS also allows you to ignore the separation of concerns, if you like, and instead apply code to handle all styles. Frameworks such as React take this approach without requiring any changes to the CSS language or architecture.
While Android and iOS are fairly rigid about how to style interface controls, the Web has many options and you can choose the one that best meets your actual needs.
CSS is a simple language and an excellent compilation target
CSS is a relatively simple language. At the top, CSS is nothing more than a collection of selectors that define a series of key-value pairs. This simplicity makes a lot of things possible.
One of these is transpilers. Because CSS is relatively simple, translators like SASS and LESS can innovate on top of the CSS language and experiment with many powerful new features. Tools like SASS and LESS not only improve development efficiency, but also affect the CSS standard itself, as features like CSS variables are now available in most major browsers.
The simplicity of CSS brings more than just translators. Every theme Builder or drag & drop building tool you see on the Web probably stems from the simplicity of CSS. There is no such thing as a theme builder in the iOS and Android world, because the output of the tool must be a complete iOS or Android app, and a complete app is not that easy to develop. (There is no iOS/Android theme builder, more things like app templates or app launchers)
One more thing: do you know how great the browser developer tools are? You can easily debug the look and feel of your application, another sign of the simplicity of CSS. Neither iOS nor Android has the same visual developer tools available on the Web.
One final example: The NativeScript project allows developers to control the styling of iOS and Android controls using a subset of CSS, such as Button {color: blue; } controls the style of UIButton or Android.widget. Button. We can do this purely because CSS is a flexible and easily parsed language.
CSS lets you do some great things
Finally, one of the most important reasons CSS is great is that developers can develop a range of things with a few simple selectors and style rules. The web is full of “10 Great EXAMPLES of CSS only” posts to prove it, and here are a few of my favorite examples.
The following is a wonderful case, click the picture to view the source code:
- Case 1:
- Case 2:
- Case 3:
conclusion
So CSS doesn’t have pits? B: of course. The box model is a bit weird, flexbox isn’t that easy to get started with, and features like CSS variables would have been better years ago.
Every style system has its drawbacks, but CSS’s flexibility, simplicity, and power have stood the test of time and helped make the Web the very powerful development platform it is today. I’m happy to defend CSS against its trolls, and I encourage you to do the same.
Caption image fromValentines by Misha Gardner
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. Android, iOS, React, front end, back end, product, design, etc. Keep an eye on the Nuggets Translation project for more quality translations.