Archiwum kategorii: CSS

One Invalid Pseudo Selector Equals an Entire Ignored Selector

Post pobrano z: One Invalid Pseudo Selector Equals an Entire Ignored Selector

Perhaps you know this one: if any part of a selector is invalid, it invalidates the whole selector. For example:

div, span::butt {
  background: red;
}

Even though div is a perfectly valid selector, span:butt is not, thus the entire selector is invalidated — neither divs nor span::butt elements on the page will have a red background.

Normally that's not a terribly huge problem. It may even be even useful, depending on the situation. But there are plenty of situations where it has kind of been a pain in the, uh, <code>:butt.

Here’s a classic:

::selection {
  background: lightblue;
}

For a long time, Firefox didn’t understand that selector, and required a vendor prefix (::-moz-selection) to get the same effect. (This is no longer the case in Firefox 62+, but you take the point.)

In other words, this wasn’t possible:

/* would break for everyone */
::selection, ::-moz-selection {
  background: lightblue;
}

That would break for browsers that understood ::selection and break for Firefox that only understood ::-moz-selection. It made it ripe territory for a preprocessor @mixin, that’s for sure.

That was annoying enough that browsers have apparently fixed it. In a conversation with Estelle Weyl, I learned that this is being changed. She wrote in the MDN docs:

Generally, if there is an invalid pseudo-element or pseudo-class within in a chain or group of selectors, the whole selector list is invalid. If a pseudo-element (but not pseudo-class) has a -webkit- prefix, As of Firefox 63, Blink, Webkit and Gecko browsers assume it is valid, not invalidating the selector list.

This isn’t for any selector; it’s specifically for pseudo-elements. That is, double colons (::).

Here’s a test:

See the Pen Ignored Invalid Selecotrs??? by Chris Coyier (@chriscoyier) on CodePen.

I’d call that a positive change.

The post One Invalid Pseudo Selector Equals an Entire Ignored Selector appeared first on CSS-Tricks.

CSS Only Floated Labels with :placeholder-shown pseudo class

Post pobrano z: CSS Only Floated Labels with :placeholder-shown pseudo class

The floated label technique has been around for a good long while and the general idea is this: we have an text input with the placeholder attribute acting as a label. When a user types into that input, the label moves from inside the input to outside of it.

Like so:

Although I don’t see this pattern used on the web all that much, I do think it’s an interesting one! There are different approaches to it, but Nick Salloum describes a new one using a combination of :not and :placeholder-shown:

This UI technique does indeed slightly bend the definitions of label and placeholder listed above, in the sense that we’re giving the placeholder more initial importance in having to explain the input to the user, but it’s a tradeoff for a neat UI component, and one that I’m personally comfortable making.

I wonder if there are other peculiar ways :not and :placeholder-shown could be put to use.

Direct Link to ArticlePermalink

The post CSS Only Floated Labels with :placeholder-shown pseudo class appeared first on CSS-Tricks.

Nested Links

Post pobrano z: Nested Links

The other day I posted an image, quite literally as a thought exercise, about how you might accomplish „nested” links. That is, a big container that is linked to one URL that contains a smaller container or text link inside of it that goes to another URL. That’s harder than it might seem at first glance. The main reason being that…

<!-- this is invalid and won't render as expected -->
<a href="#one">
  Outside
  <a href="#two">
    Inside
  </a>
</a>

Eric Meyer once called for more flexible linking, but even that doesn’t quite handle a situation where one link is nested inside another.

Here’s what happens with that HTML, by the way:

The nested link gets kicked out.

My first inclination would be to simply not nest the links in the markup, but make them appear nested visually. Some folks replied to the tweet, including Nathan Smith, who shared that same thought: have a relatively positioned parent element and absolutely position both links. The larger one could fill up the whole area and the smaller one could sit on top of it.

See the Pen „Nested” links by Nathan Smith (@nathansmith) on CodePen.

It’s finicky, as you’ll need magic numbers to some degree to handle the spacing and variable content.

My second inclination would be to deal with it in JavaScript.

<div 
  onclick="window.location='https://codepen.io'"
  style="cursor: pointer;"
  tab-index="1"
>
  Outside
  <a href="https://css-tricks.com">
    Inside
  </a>
</div>

I have literally no idea how kosher that is from an accessibility perspective. It looks gross to me so I’m just going to assume it’s bad news.

Speaking of accessibility, Heydon Pickering has a whole article about card components which is a popular design pattern where this situation often comes up. His solution is to have a relatively positioned parent element, then a normally-placed and functional main link. That first link has an absolutely positioned pseudo-element on it covering the entire card. Any sub-links are relatively positioned and come after the initial link, so they’d sit on top of the first link by way of z-index.

Demo with author link.

And speaking of stacking pseudos, that’s the approach Sean Curtis uses here:

See the Pen Pretend nested links by Sean Curtis (@seancurtis) on CodePen.

Other solutions in the „crafty” territory might be:

Sara Soueidan responded with her own post!

I had the same requirement a couple of years ago when I was building the front-end foundation for Smashing Magazine. So I thought I’d write my response to Chris’s thread out in the form of a blog post.

Sara has written about this with much more detail and care than I have here, so definitely check that out. It looks like both she and Heydon have landed on nearly the same solution, with the pseudo-element cover that contains sub-links poking above it as needed.

Have you ever done it another way? Plenty of UX and a11y to think abbout!

The post Nested Links appeared first on CSS-Tricks.

Nested Links

Post pobrano z: Nested Links

The other day I posted an image, quite literally as a thought exercise, about how you might accomplish „nested” links. That is, a big container that is linked to one URL that contains a smaller container or text link inside of it that goes to another URL. That’s harder than it might seem at first glance. The main reason being that…

<!-- this is invalid and won't render as expected -->
<a href="#one">
  Outside
  <a href="#two">
    Inside
  </a>
</a>

Eric Meyer once called for more flexible linking, but even that doesn’t quite handle a situation where one link is nested inside another.

Here’s what happens with that HTML, by the way:

The nested link gets kicked out.

My first inclination would be to simply not nest the links in the markup, but make them appear nested visually. Some folks replied to the tweet, including Nathan Smith, who shared that same thought: have a relatively positioned parent element and absolutely position both links. The larger one could fill up the whole area and the smaller one could sit on top of it.

See the Pen „Nested” links by Nathan Smith (@nathansmith) on CodePen.

It’s finicky, as you’ll need magic numbers to some degree to handle the spacing and variable content.

My second inclination would be to deal with it in JavaScript.

<div 
  onclick="window.location='https://codepen.io'"
  style="cursor: pointer;"
  tab-index="1"
>
  Outside
  <a href="https://css-tricks.com">
    Inside
  </a>
</div>

I have literally no idea how kosher that is from an accessibility perspective. It looks gross to me so I’m just going to assume it’s bad news.

Speaking of accessibility, Heydon Pickering has a whole article about card components which is a popular design pattern where this situation often comes up. His solution is to have a relatively positioned parent element, then a normally-placed and functional main link. That first link has an absolutely positioned pseudo-element on it covering the entire card. Any sub-links are relatively positioned and come after the initial link, so they’d sit on top of the first link by way of z-index.

Demo with author link.

And speaking of stacking pseudos, that’s the approach Sean Curtis uses here:

See the Pen Pretend nested links by Sean Curtis (@seancurtis) on CodePen.

Other solutions in the „crafty” territory might be:

Sara Soueidan responded with her own post!

I had the same requirement a couple of years ago when I was building the front-end foundation for Smashing Magazine. So I thought I’d write my response to Chris’s thread out in the form of a blog post.

Sara has written about this with much more detail and care than I have here, so definitely check that out. It looks like both she and Heydon have landed on nearly the same solution, with the pseudo-element cover that contains sub-links poking above it as needed.

Have you ever done it another way? Plenty of UX and a11y to think abbout!

The post Nested Links appeared first on CSS-Tricks.

Test out the cloud platform developers love for free with a $100 credit

Post pobrano z: Test out the cloud platform developers love for free with a $100 credit

(This is a sponsored post.)

DigitalOcean invites you to experience a better, faster and simpler cloud platform designed to scale based on your needs. Get started for free with a $100 credit toward your first project and discover why the most innovative companies are already hosting on DigitalOcean.

Direct Link to ArticlePermalink

The post Test out the cloud platform developers love for free with a $100 credit appeared first on CSS-Tricks.

A Minimal JavaScript Setup

Post pobrano z: A Minimal JavaScript Setup

Some people prefer to write JavaScript with React. For others, it’s Vue or jQuery. For others still, it is their own set of tools or a completely blank document. Some setups are minimal, some allow you to get things done quickly, and some are crazy powerful, allowing you to build complex and maintainable applications. Every setup has advantages and disadvantages, but positives usually outweigh negatives when it comes to popular frameworks verified and vetted by an active community.

React and Vue are powerful JavaScript frameworks. Of course they are — that’s why both are trending so high in overall usage. But what is it that makes those, and other frameworks, so powerful? Is it the speed? Portability to other platforms like native desktop and mobile? Support of the huge community?

The success of a development team starts with an agreement. An agreement of how things are done. Without an agreement, code would get messy, and the software unsustainable quite quickly, even for relatively small projects. Therefore, a lot (if not most) of the power of a framework lies within this agreement. The ability to define conventions and common patterns that everyone adheres to. That idea is applicable to any framework, JavaScript or not. Those „rules” are essential to development and bring teams maintainability at any size, reusability of code, and the ability to share work with a community in a form anyone will understand. That’s why we can web search for some component/plugin that solves our problem rather than writing something on our own. We rely on open-source alternatives, no matter what framework we use.

Unfortunately, there are downsides to frameworks. As Adrian Holovaty (one of the Django creators) explains in his talk, frameworks tend to get bulky and bloated with features for one particular use case. It could be the inclusion of a really good idea. It could also be a desire to provide a one-size-fits-all solution for anyone and everyone’s needs. It could be to remain popular. Either way, there are downsides to frameworks in light of all the upsides they also have.

In server-rendered world, where we work with content that’s delivered to the browser from a server, this „framework mission” is filled with skills, ideas, and solutions that people share with co-workers, friends, and others. They tend to adopt consistent development rules and enforce them within their teams or companies, rather than relying on a predefined framework. For a long time, it’s been jQuery that has allowed people to share and reuse code on a global scale with its plugins — but that era is fading as new frameworks are entering the fold.

Let’s take a look at some core points that any framework — custom or not — ought to consider essential for encouraging a maintainable and reusable codebase.

Naming conventions

Some might say that naming is the hardest part of development. Whether it’s naming JavaScript variables, HTML classes, or any other number of things, a naming convention has a big impact on how we work together because it adds context and meaning to our code. A good example of a naming convention is BEM, a CSS methodology created by the folks at Yandex and adopted by many, many front-enders. That sort of standardization and consistency can help inform our objective, which is to have a standard convention for naming JavaScript selectors.

This situation might seem familiar: you revisit a project after a few months and you see some behavior happening on the page — maybe something you want to modify or fix. However, finding the source of that behavior can be a tricky thing. Is it the id attribute I should search for? Is it one of the classes? Maybe the data attribute for this particular element?

I think you get the point. What helps is having some kind of convention to simplify the process and make everyone work with the same names. And it doesn’t really matter if we’re going with classes (e.g. js-[name]) or data attributes (e.g. data-name="[name]"). All that matters is that the names conform to the same style. Surely enough, any framework you will meet will enforce a naming convention of some sort as well, whether it’s React, Vue, Bootstrap, Foundation, etc.

Scope

A developer will likely struggle with JavaScript scope at some point in time, but we are specifically focusing on DOM scope here. No matter what you do with JavaScript, you’re using it to affect some DOM element. Limiting parts of the code to a DOM element encourages maintainability and makes code more modular. Components in both React and Vue operate in a similar fashion, although their „component” concept is different than the standard DOM. Still, the idea scopes the code to a DOM element that is rendered by those components.

While we’re on the topic of DOM manipulation, referencing elements within the root element of the component is super helpful because it help avoids the constant need to select elements. React and Vue do this out of the box in a very good way.

Lifecycle

In the past, the page lifecycle was very straightforward: the browser loaded the page and the browser left the page. Creating or removing event listeners, or making code run at the right time was much simpler, as you would simply create everything you need on load, and rarely bother with disabling your code, since the browser would do it for you by default.

Nowadays, the lifecycle tends to be much more dynamic, thanks to state management and the way we prefer to manipulate changes directly to the DOM or load the contents of pages with JavaScript. Unfortunately, that usually brings some issues where you may need to re-run parts of your code at certain times.

I can’t tell how many times in my life I’ve had to play around with code to get my event handlers to run correctly after re-writing part of the DOM. Sometimes it is possible to solve this with event delegation. Other times, your code handlers don’t run at all or run several times because they are suddenly attached twice.

Another use case would be the need to create an instance of libraries after changing the DOM, like „fake selects.”

In any case, the lifecycle is important and limiting your code to a DOM element certainly helps here as well, since you know that the code applied to that element needs to be re-run in case the element is re-rendered.

Frameworks do the same with functions as componentDidMount or componentDidUpdate, which give you an easy way of running code exactly when you need it.

Reusability

Copying code from somewhere else and reusing it is super common. Who hasn’t used a snippet from a past project or an answer from StackOverflow, right? People even invented services like npm meant for one thing: to easily share and reuse code. There is no need to reinvent the wheel and sharing code with others is something that is convenient, handy, and often more efficient than spinning something up from scratch.

Components, whether it’s React, Vue, or any other building block of a framework encourage reusability by having a wrapper around a piece of code that serves some specific purpose. A standardized wrapper with an enforced format. I would say this is more of a side effect of having some base we can build on, than an intentional effort for reusability, as any base will always need some standard format of a code it can run, the same way programming languages have a syntax we need to follow… but it is a super convenient and useful side effect, for sure. By combining this gained reusability with package managers like Yarn, and bundlers like webpack, we can suddenly make code written by many developers around the world work together in our app with almost no effort.

While not all code is open-source and shareable, a common structure will help folks in smaller teams as well, so anyone is able to understand most of the code written within the team without having to consult its author.

DOM manipulation with performance in mind

Reading and writing to the DOM is costly. Developers of front-end frameworks keep that in mind and try to optimize as much as possible with states, virtual DOM and other methods to make changes to the DOM when it’s needed and where it’s needed… and so should we. While we’re more concerned with server-rendered HTML, most of the code ends up reading or writing to the DOM. After all, that’s what JavaScript is for.

While most of the changes of the DOM are minimal, they can also occur quite often. A nice example of frequent reading/writing is executing a script on page scroll. Ideally, we would like to avoid adding classes, attributes or changing the contents of elements directly in the handler, even if we write the same classes, attributes or contents because our changes still get processed by the browser and are still expensive, even when nothing changes for the user.

Size

Last, but not least: size. Size is critical or at least should be for a framework. The code discussed in this article is meant to be used as a base across many projects. It should be as small as possible and avoid any unnecessary code that could be added manually for one-off use cases. Ideally, it should be modular so that we can pull pieces of it out à la carte, based on the specific needs for the project at hand.

While the size of self-written code is usually reasonable, many projects end up having at least some dependencies/libraries to fill in gaps, and those can make things quite bulky really fast. Let’s say we have a carousel on a top-level page of a site and some charts somewhere deeper. We can turn to existing libraries that would handle these things for us, like slick carousel (10 KB minified/gzipped, excluding jQuery) and highcharts (73 KB minified/gzipped). That’s over 80 KB of code and I’d bet that not every byte is needed for our project. As Addy Osmani explains, JavaScript is expensive and its size is not the same as other assets on a page. It’s worth keeping that in mind the next time you find yourself reaching for a library, though it shouldn’t discourage you from doing it if the positives outweigh the negatives.

A look at a minimal solution we call Gia

Let’s take a look at something I’ve been working on and using for a while with my team at Giant. We like JavaScript and we want to work directly with JavaScript rather than a framework. But at the same time, we need the maintainability and reusability that frameworks offer. We tried to take some concepts from popular frameworks and apply them to a server-rendered website where the options for a JavaScript setup are so wide, and yet so limited.

We’ll go through some basic features of our setup and focus on how it solves the points we’ve covered so far. Note that many of the solutions to our needs are directly inspired by big frameworks, so if you see some similarities, know that it’s not an accident. We call it Gia (get it, like short for Giant?!) and you can get it from npm and find the source code on GitHub.

Gia, like many frameworks, is built around components that give you a basic building block and some advantages we’ll touch on in a bit. But don’t confuse Gia components with the component concepts used by React and Vue, where all your HTML is a product of the component. This is different.

In Gia, a component is a wrapper for your own code that runs in the scope of a DOM element, and the instance of a component is stored within the element itself. As a result, an instance is automatically removed from the memory by the garbage collector in case the element is removed from the DOM. The source code of the component can be found here and is fairly simple.

Apart from a component, Gia includes several helpers to apply, destroy and work with the component instance or communicate between components (with standard eventbus included for convenience).

Let’s start with a basic setup. Gia is using an attribute to select elements, along with the name of the component to be executed (i.e. g-component="[component name]"). This enforces a consistent naming convention. Running the loadComponents function creates the instances defined with the g-component attribute.

See the Pen Basic component by Georgy Marchuk (@gmrchk) on CodePen.

Gia components also allow us to easily select elements within the root element with the g-ref attribute. All that needs to be done is to define the refs that are expected and whether we’re working with a single element or an array of them. Reference is then accessible in the this.ref object within the component.

See the Pen Component with ref elements by Georgy Marchuk (@gmrchk) on CodePen.

As a bonus, default options can be defined in the component, which are automatically rewritten by any options included in g-options attribute.

See the Pen Component with options by Georgy Marchuk (@gmrchk) on CodePen.

The component includes methods that are executed at different times, in order to solve the lifecycle issue. Here’s an example that shows how a component can be initialized or removed:

See the Pen load/remove components by Georgy Marchuk (@gmrchk) on CodePen.

Notice how loadComponents function doesn’t apply the same component when it already exists.

It is not necessary to remove listeners attached to the root element of a component or elements within it before re-rendering them since the elements would be removed from the DOM anyway. However, there can be some listeners created on global objects (e.g. window), like the ones used for scroll handling. In this case, it is necessary to remove the listener manually before destroying the component instance in order to avoid memory leaks.

The concept of a component scoped to a DOM element is similar in its nature to React and Vue components, but with a key exception that the DOM structure is outside of the component. As a result, we have to make sure it fits the component. Defining the ref elements certainly helps, as Gia component will tell you when the required refs are not present. That makes the component reusable. The following is example implementation of a basic carousel that could be easily reused or shared:

See the Pen Basic carousel component by Georgy Marchuk (@gmrchk) on CodePen.

While we’re talking about reusability, it’s important to mention that components don’t have to be reused in their existing state. In other words, we can extend them to create new components as any other JavaScript class. That means we can prepare a general component and build upon it.

To give an example, a component that would give us the distance between the cursor and the center of an element seems like a thing that could be useful someday. Such a component can be found here. After having that ready, it’s ridiculously easy to build upon it and work with provided numbers, as the next example shows in the render function, although we could argue about the usefulness of this particular example.

See the Pen ZMXMJo by Georgy Marchuk (@gmrchk) on CodePen.

Let’s try to look into optimized DOM manipulations. Detecting if a change to the DOM is supposed to happen can be manually stored or checked without directly accessing the DOM, but that tends to be a lot of work which we might want to avoid.

This is where Gia really drew inspiration from React, with simple, stripped down component state management. The state of a component is set similarly to states in React, using a setState function.

That said, there is no rendering involved in our component. The content is rendered by the server, so we need to make a use of the changes in state elsewhere. The state changes are evaluated and any actual changes are sent to the stateChange method of a component. Ideally, any interaction between the component and the DOM would be handled in this function. In case some part of the state doesn’t change, it won’t be present in the stateChanges object passed into a function and therefore won’t be processed — the DOM won’t be touched without it being truly necessary.

Check the following example with a component showing sections that are visible in the viewport:

See the Pen Sections in viewport component by Georgy Marchuk (@gmrchk) on CodePen.

Notice how writing to the DOM (visualized by the blink) is only done for items where the state actually changes.

Now we are getting to my favorite part! Gia is truly minimal. The entire bundle containing all the code, including all the helpers, takes up a measly 2.68 KB (minified/gzipped). Not to mention that you most likely won’t need all of Gia’s parts and would end up importing even less with a bundler.

As mentioned earlier, the size of the code can rapidly increase by including third-party dependencies. That’s why Gia also includes code splitting support where you can define a dependency for a component, which will only be loaded when the component is being initialized for the first time, without any additional setup required to the bundler. That way, the bulky libraries used somewhere deep within your site or application don’t have to slow things down.

In case you decide one day that you really want to take advantage of all the goodies big frameworks can offer somewhere in your code, there is nothing easier than just loading it like any other dependency for the component.

class SampleComponent extends Component {
  async require() {
    this.vue = await import('vue');
  }

  mount() {
    new this.vue({
      el: this.element,
    });
  }
}

Conclusion

I guess the main point of this article is that you don’t need a framework to write maintainable and reusable code. Following and enforcing a few concepts (that frameworks use as well) can take you far on its own. While Gia is minimal and does not have many of the robust features offered by big players, like React and Vue, it still helps us get that clean structure that is so important in the long term. It includes some more interesting stuff that didn’t make the cut here. If you like it so far, go check it out!

GitHub Repo

There are lots and lots of use cases, and different needs require different approaches. Various frameworks can do plenty of the work for you; in other cases, they may be constraining.

What is your minimal setup and how do you account for the points we covered here? Do you prefer a framework or non-framework environment? Do you use frameworks in combination with static site generators like Gatsby? Let me know!

The post A Minimal JavaScript Setup appeared first on CSS-Tricks.

Developing With Automad

Post pobrano z: Developing With Automad

Selecting the right CMS for a blog or website can be difficult. Every web project has its own needs and requirements, meaning one CMS may be a better fit for one site but not so much for a different site. Simple solutions might be lacking some essential features, while more complex systems can create easily overhead for a given task.

I want to cover Automad, a CMS that is less-known than, say, a behemoth like WordPress, but still offers some powerful features like it while maintaining the nimbleness of smaller, simpler solutions, like static site generators.

Specifically, Automad fills a gap between larger and smaller offerings in a few key ways:

  • It is file-based, but does not require a database. This ensures quick setup, portability, security, speed, and easy deployment.
  • Even without a database, it offers database features like searching, tagging, filtering, and sorting.
  • A multi-layer caching engine caches content stored in the file system efficiently.
  • The browser-based dashboard and the in-page (“live”) edit mode allows for intuitive content management.

But what makes Automad really different, is its integrated template engine. Templating is a core requirement for may CMSs because it creates and sets the base for a site’s visual display. Since Automad’s template engine is so close to the core, it allows you to create templates with complex navigations and to batch process images using a clean and short syntax. You’ll feel the difference once you get your hands on it, and we’ll walk through an example together in just a bit.

But first, a quick overview of templating

As a designer or a developer, you’re probably curious about how to develop themes and templates for Automad. I mean, it’s the crux for why any of us really use a CMS in the first place. If you’ve done any level of theming with WordPress, then working with Automad will feel vaguely familiar, and perhaps even easier.

The minimal requirement for creating an Automad theme is a single .php file and a theme.json file bundled together in a subdirectory you create inside the top-level /packages directory in a default Automad installation:

packages/
  yourTheme/
    yourTemplate.php
    theme.json

The tutorial package shipped with Automad provides a good starting point for understanding the basic concepts of themes.

A look at the syntax used in Automad templates

While it is possible to write templates in plain PHP, it is not required and actually not recommended. The reason is that Automad’s own template syntax is shorter, more readable, and integrates well with the user interface by automatically listing all of the used variables in the dashboard. It can be seamlessly mixed into HTML markup.

Basically, the syntax can be split into two groups:

  1. Echoing content: @{ variable }
  2. Statements, like functions, loops and conditionals: <@ function @> or <@ statement @>…<@ end @>

Echo content

Let’s say we want to pull the body content for a post into a template and we have a variable set up for that called text. In WordPress, this would be a global variable (the_content) that is called in PHP:

<?php the_content(); ?>

In Automad, we can do the same without PHP:

<p>@{ text }</p>

It is possible to manipulate the output of variables by passing the value to a function using the pipe (|) operator. The following example shows how to shorten a given text to a maximum of 100 characters without cutting words:

@{ text | shorten (100) }

This would be the same of thing you might do to define the excerpt of a post in WordPress using a function:

/* Limit excerpt to 20 words */
function my_custom_excerpt_length( $length ) {
    return 20;
}
add_filter( 'excerpt_length', 'wpdocs_custom_excerpt_length', 999 )
}

One of the key benefits of some CMS solutions, like Jeykll, is that using Markdown to create site content is a native feature. Automad can do the same. Let’s say we want to convert Markdown text to HTML. It’s pretty darn simple (and efficient) using the pipe operator:

@{ text | markdown }

Using statements

Statements are a handy way to define content and display it conditionally. Unlike variables, statements are wrapped in <@ … @> delimiters. The following example can be used to create a simple top level menu by using the nav function:

<@ nav { context: "/", class: "nav" } @>

Let’s say you want to display your post content by default but display a fallback if that content does not exist for some reason. That’s where we can put conditional statements and control structures to use:

<# If the post content exists then display... #>
<@ if @{ text } @>
  <p>...</p>

<# Otherwise, display this... #>
<@ else @>
  <p>Sorry, no content here!</p>

<# OK, no more conditions. #>
<@ end @>

Want to create a loop? This is where display a list of posts or any repeatable content that matches a condition is super useful. We can do that in Automad by providing one or more glob patterns in a foreach loop.

For example, let’s display all JPG and PNG images for a post cropped at 400x300 with their captions:

<@ foreach in "*.jpg, *.png" { width: 400, height: 300, crop: true } @>
  <img src="@{:fileResized}" width="@{:widthResized}" height="@{:heightResized}">
  <p>@{:caption}</p>
<@ end @>

Did you catch that?! As shown by this example, a remarkable Automad feature is the ability to embed resizing options for each matching file inside the loop statement. No more complicated functions to register sizes that then need to be called in the template!

It’s worth noting that foreach loops can also be used to iterate over objects. Automad knows multiple types of objects. One of the most important objects is pagelist because of its ability to output all of the pages on the site, like you might want to do when building navigation. When iterating a pagelist, the context changes with every iteration to the current page in the loop. That way, it is possible to use page variables within the loop’s code block.

To configure the pagelist, we can use the newPagelist function like this:

<@ newPagelist { context: "/", type: "children" } @>
<ul>
  <@ foreach in pagelist @>
    <li><a href="@{ url }">@{ title }</a></li>
  <@ end @>
</ul>

A sneak peek behind the scenes for you super geeks 🤓

Automad’s template interpreter is written in pure PHP and it processes templates on the fly. Therefore, no extra build process is required at all. The list of system requirements is also rather short. A web server (Apache or Nginx) and PHP 5.4+ is already enough to run a site. Pages are only rendered when content has changed or after system updates.

Automad’s multi-layer caching engine stores the rendered pages in separate .html files as well as all crawled data in the file system as a kind of content object. That object is also used to speed up page searching and filtering.

Due to that mechanism, it is possible to either edit the content of a site directly in production online using the browser-based dashboard or edit a site locally and deploy it via Git or plain rsync.

Let’s write some code!

The best way to get acquainted with anything on the web is to just build websites. Here are some examples of how we’d get started with that using Automad.

Example 1: Recursive navigation

Creating a site-tree navigation is a good example for using recursion in templates. Conceptually, creating such a recursive navigation can be split into three steps:

  1. Defining a reusable snippet of code to create a single branch of the site-tree which calls itself conditionally
  2. Configuring a dynamic pagelist which automatically only contains children of its current context
  3. Defining the root page of the site-tree (for instance the homepage) and call the recursive snippet initially

Let’s break those steps down into greater detail…

Defining a reusable snippet of code

In Automad, blocks of code can be defined to be reused at a later point by using the snippet keyword. Regarding this example, the following snippet will call itself conditionally when looping through a pagelist and the active page of the current iteration itself has children pages:

<@ snippet navigation @>  
  <ul class="menu-list">       
    <@ foreach in pagelist @>
      <li>
        <a href="@{ url }">@{ title }</a>
        <# Call snippet recursively. #>
        <@ navigation @>
      </li>
    <@ end @>
  </ul>
<@ end @>
Configuring a dynamic pagelist

The pagelist has to be configured a children type. The context (or parent page) will always change recursively within the snippet defined above in that way. The pagelist will automatically only contain children pages of the currently processed page.

<@ newPagelist { 
  type: 'children'
} @>
Defining the root page

In the last step, the root context of the navigation tree has to be defined and the snippet has to be called once to initiate the recursion. The with statement is used here to change the context to the homepage.

<div class="menu">
  <@ with '/' @>
    <@ navigation @>
  <@ end @>
</div>

A complete working tutorial template is already included in Automad.

Example 2: Working with files

Since images are super important for content management, working with them should be as easy and intuitive as possible. Automad’s template language provides handy methods for basic image processing, like resizing and cropping. When using a single image or iterating a set of images, resizing options can be passed to a with statement or foreach loop. Check out the <a href="https://dev.automad.org/tutorials/working-with-images"Working with Images tutorial that ships with Automad to get started quickly.

<@ foreach in '*.jpg, *.png' { width: 400, height: 300, crop: true } @>
  <# Code to be used for each image in the filelist. #>
  <img 
  src="@{ :fileResized }" 
  alt="@{ :basename }"
  title="@{ :file }"
  width="@{ :widthResized }"
  height="@{ :heightResized }"
  >
  <p>@{ :caption | markdown }</p>
<@ else @>
  <# Code to be used when the list of images is empty. #>
<@ end @>

Instead of using a glob pattern in the foreach loop, it is also possible to use the filelist object.

If you look at the example code above, you will notice the use of certain runtime variables to access image properties within a code block. While the :file variable represents the original file, :fileResized refers to path of the resized and cached version. The :caption variable enables you to get the caption text stored along with the file.


What will you build?

We merely scratched the surface of Automad here, but hopefully everything we covered gives you a good idea of the possibilities it provides for content management. While there is no one-size-fits-all mold in the CMS world, there will likely be scenarios where a CMS that sits somewhere between the robust and slimmed-down options will come in handy.

Additional Resources

The post Developing With Automad appeared first on CSS-Tricks.

Developing With Automad

Post pobrano z: Developing With Automad

Selecting the right CMS for a blog or website can be difficult. Every web project has its own needs and requirements, meaning one CMS may be a better fit for one site but not so much for a different site. Simple solutions might be lacking some essential features, while more complex systems can create easily overhead for a given task.

I want to cover Automad, a CMS that is less-known than, say, a behemoth like WordPress, but still offers some powerful features like it while maintaining the nimbleness of smaller, simpler solutions, like static site generators.

Specifically, Automad fills a gap between larger and smaller offerings in a few key ways:

  • It is file-based, but does not require a database. This ensures quick setup, portability, security, speed, and easy deployment.
  • Even without a database, it offers database features like searching, tagging, filtering, and sorting.
  • A multi-layer caching engine caches content stored in the file system efficiently.
  • The browser-based dashboard and the in-page (“live”) edit mode allows for intuitive content management.

But what makes Automad really different, is its integrated template engine. Templating is a core requirement for may CMSs because it creates and sets the base for a site’s visual display. Since Automad’s template engine is so close to the core, it allows you to create templates with complex navigations and to batch process images using a clean and short syntax. You’ll feel the difference once you get your hands on it, and we’ll walk through an example together in just a bit.

But first, a quick overview of templating

As a designer or a developer, you’re probably curious about how to develop themes and templates for Automad. I mean, it’s the crux for why any of us really use a CMS in the first place. If you’ve done any level of theming with WordPress, then working with Automad will feel vaguely familiar, and perhaps even easier.

The minimal requirement for creating an Automad theme is a single .php file and a theme.json file bundled together in a subdirectory you create inside the top-level /packages directory in a default Automad installation:

packages/
  yourTheme/
    yourTemplate.php
    theme.json

The tutorial package shipped with Automad provides a good starting point for understanding the basic concepts of themes.

A look at the syntax used in Automad templates

While it is possible to write templates in plain PHP, it is not required and actually not recommended. The reason is that Automad’s own template syntax is shorter, more readable, and integrates well with the user interface by automatically listing all of the used variables in the dashboard. It can be seamlessly mixed into HTML markup.

Basically, the syntax can be split into two groups:

  1. Echoing content: @{ variable }
  2. Statements, like functions, loops and conditionals: <@ function @> or <@ statement @>…<@ end @>

Echo content

Let’s say we want to pull the body content for a post into a template and we have a variable set up for that called text. In WordPress, this would be a global variable (the_content) that is called in PHP:

<?php the_content(); ?>

In Automad, we can do the same without PHP:

<p>@{ text }</p>

It is possible to manipulate the output of variables by passing the value to a function using the pipe (|) operator. The following example shows how to shorten a given text to a maximum of 100 characters without cutting words:

@{ text | shorten (100) }

This would be the same of thing you might do to define the excerpt of a post in WordPress using a function:

/* Limit excerpt to 20 words */
function my_custom_excerpt_length( $length ) {
    return 20;
}
add_filter( 'excerpt_length', 'wpdocs_custom_excerpt_length', 999 )
}

One of the key benefits of some CMS solutions, like Jeykll, is that using Markdown to create site content is a native feature. Automad can do the same. Let’s say we want to convert Markdown text to HTML. It’s pretty darn simple (and efficient) using the pipe operator:

@{ text | markdown }

Using statements

Statements are a handy way to define content and display it conditionally. Unlike variables, statements are wrapped in <@ … @> delimiters. The following example can be used to create a simple top level menu by using the nav function:

<@ nav { context: "/", class: "nav" } @>

Let’s say you want to display your post content by default but display a fallback if that content does not exist for some reason. That’s where we can put conditional statements and control structures to use:

<# If the post content exists then display... #>
<@ if @{ text } @>
  <p>...</p>

<# Otherwise, display this... #>
<@ else @>
  <p>Sorry, no content here!</p>

<# OK, no more conditions. #>
<@ end @>

Want to create a loop? This is where display a list of posts or any repeatable content that matches a condition is super useful. We can do that in Automad by providing one or more glob patterns in a foreach loop.

For example, let’s display all JPG and PNG images for a post cropped at 400x300 with their captions:

<@ foreach in "*.jpg, *.png" { width: 400, height: 300, crop: true } @>
  <img src="@{:fileResized}" width="@{:widthResized}" height="@{:heightResized}">
  <p>@{:caption}</p>
<@ end @>

Did you catch that?! As shown by this example, a remarkable Automad feature is the ability to embed resizing options for each matching file inside the loop statement. No more complicated functions to register sizes that then need to be called in the template!

It’s worth noting that foreach loops can also be used to iterate over objects. Automad knows multiple types of objects. One of the most important objects is pagelist because of its ability to output all of the pages on the site, like you might want to do when building navigation. When iterating a pagelist, the context changes with every iteration to the current page in the loop. That way, it is possible to use page variables within the loop’s code block.

To configure the pagelist, we can use the newPagelist function like this:

<@ newPagelist { context: "/", type: "children" } @>
<ul>
  <@ foreach in pagelist @>
    <li><a href="@{ url }">@{ title }</a></li>
  <@ end @>
</ul>

A sneak peek behind the scenes for you super geeks 🤓

Automad’s template interpreter is written in pure PHP and it processes templates on the fly. Therefore, no extra build process is required at all. The list of system requirements is also rather short. A web server (Apache or Nginx) and PHP 5.4+ is already enough to run a site. Pages are only rendered when content has changed or after system updates.

Automad’s multi-layer caching engine stores the rendered pages in separate .html files as well as all crawled data in the file system as a kind of content object. That object is also used to speed up page searching and filtering.

Due to that mechanism, it is possible to either edit the content of a site directly in production online using the browser-based dashboard or edit a site locally and deploy it via Git or plain rsync.

Let’s write some code!

The best way to get acquainted with anything on the web is to just build websites. Here are some examples of how we’d get started with that using Automad.

Example 1: Recursive navigation

Creating a site-tree navigation is a good example for using recursion in templates. Conceptually, creating such a recursive navigation can be split into three steps:

  1. Defining a reusable snippet of code to create a single branch of the site-tree which calls itself conditionally
  2. Configuring a dynamic pagelist which automatically only contains children of its current context
  3. Defining the root page of the site-tree (for instance the homepage) and call the recursive snippet initially

Let’s break those steps down into greater detail…

Defining a reusable snippet of code

In Automad, blocks of code can be defined to be reused at a later point by using the snippet keyword. Regarding this example, the following snippet will call itself conditionally when looping through a pagelist and the active page of the current iteration itself has children pages:

<@ snippet navigation @>  
  <ul class="menu-list">       
    <@ foreach in pagelist @>
      <li>
        <a href="@{ url }">@{ title }</a>
        <# Call snippet recursively. #>
        <@ navigation @>
      </li>
    <@ end @>
  </ul>
<@ end @>
Configuring a dynamic pagelist

The pagelist has to be configured a children type. The context (or parent page) will always change recursively within the snippet defined above in that way. The pagelist will automatically only contain children pages of the currently processed page.

<@ newPagelist { 
  type: 'children'
} @>
Defining the root page

In the last step, the root context of the navigation tree has to be defined and the snippet has to be called once to initiate the recursion. The with statement is used here to change the context to the homepage.

<div class="menu">
  <@ with '/' @>
    <@ navigation @>
  <@ end @>
</div>

A complete working tutorial template is already included in Automad.

Example 2: Working with files

Since images are super important for content management, working with them should be as easy and intuitive as possible. Automad’s template language provides handy methods for basic image processing, like resizing and cropping. When using a single image or iterating a set of images, resizing options can be passed to a with statement or foreach loop. Check out the <a href="https://dev.automad.org/tutorials/working-with-images"Working with Images tutorial that ships with Automad to get started quickly.

<@ foreach in '*.jpg, *.png' { width: 400, height: 300, crop: true } @>
  <# Code to be used for each image in the filelist. #>
  <img 
  src="@{ :fileResized }" 
  alt="@{ :basename }"
  title="@{ :file }"
  width="@{ :widthResized }"
  height="@{ :heightResized }"
  >
  <p>@{ :caption | markdown }</p>
<@ else @>
  <# Code to be used when the list of images is empty. #>
<@ end @>

Instead of using a glob pattern in the foreach loop, it is also possible to use the filelist object.

If you look at the example code above, you will notice the use of certain runtime variables to access image properties within a code block. While the :file variable represents the original file, :fileResized refers to path of the resized and cached version. The :caption variable enables you to get the caption text stored along with the file.


What will you build?

We merely scratched the surface of Automad here, but hopefully everything we covered gives you a good idea of the possibilities it provides for content management. While there is no one-size-fits-all mold in the CMS world, there will likely be scenarios where a CMS that sits somewhere between the robust and slimmed-down options will come in handy.

Additional Resources

The post Developing With Automad appeared first on CSS-Tricks.

All Fired Up About Specificity

Post pobrano z: All Fired Up About Specificity

You never know where the next Grand Debate™ in front-end is going to come from! Case in point: we just saw one recently based on a little Twitter poll by Max Stoiber in which 57% of people got it wrong. There were reactions ranging from the innocuous hey fun a little brain teaser! to the state of web education is in shambles and beyond.

I heard from a number of folks that they just felt sad that so many people don’t know the answer to a fairly simple question. To be fair, it was (intentionally, I’m sure) rather tricky! It wasn’t really a question about CSS — it was more about the idea that the order of HTML attributes doesn’t matter. It’s the order of CSS that does.

One extreme response I saw said that front-end stuff like this is needlessly complicated and getting it wrong is almost a point of pride. This sentiment was so strong that I heard it suggested that people who know the answer have filled their brains with useless information and that somehow makes them a worse developer. Equally extreme were suggestions that writing HTML and CSS raw like that should always be avoided in favor of tooling abstractions to „fix” these „problems.”

(Excuse the quotes there, I’m not trying to pick a side so much as to emphasize that not everyone considers these problems that need to be fixed.)

Another take was that the vibe would be different if something similar happened in JavaScript-land. The perception is that it’s embarrassing or bad not to know JavaScript basics, but not knowing HTML and CSS basics is the fault of the language, or that the value of knowing it is not worth bothering to understand.

At the same time, this poll became the perfect mirror to see the strong opinions people have about front-end practices. Fascinating, really.

Here are a few more takes from folks who chimed from their own blogs:

Keith Grant:

I hate that this has somehow become some “old guard” vs. “new guard” thing.

The problem with drawing lines like this: whichever side you find yourself on, there are some whackos out there throwing ridiculous arguments into the mix. And now people on the other side associate that viewpoint with you.

Tim Kadlec:

It doesn’t bother me too much that people are getting the question wrong. Everyone is at different stages in their career and everyone has different problems they’re facing in their daily tasks, so sure, not everyone is going to know this yet.

I do find it a bit alarming just how many folks got it wrong though.

John Allsopp:

One the one hand (and this will somewhat simplify each ‘side’, for the sake of brevity, not disrespect to either), we have those, and I’d on balance probably include myself in this camp, who’d argue that the core technologies of the Web are precisely that–foundational, and a deep understanding of them conceptually (not necessarily an encyclopedic knowledge of every syntactic aspect) is fundamental working knowledge for professional Web developers.

Kevin Ball:

With the growth of the importance of front-end development, we’re seeing the story play out again.

The systematic devaluation of CSS, and more, the people who use CSS.

The constant „mansplaining” of CSS features to women who literally are the reason it exists.

Conference speakers asked questions about whether „there is any value in people who cannot write JavaScript?”.

All of this at a time when CSS is improving faster than ever and enabling dramatic changes in web design.

This isn’t about better technology, it’s about exclusion.


Have you seen any other takes or have any of your own?

The post All Fired Up About Specificity appeared first on CSS-Tricks.

Introducing the YOOtheme Pro Page Builder

Post pobrano z: Introducing the YOOtheme Pro Page Builder

(This is a sponsored post.)

YOOtheme Pro is a powerful theme and page builder developed by YOOtheme that provides a new experience of building websites in WordPress. Designers will get an easy and exciting way to design and create websites due to premium layouts and an intuitive page builder, and developers will especially appreciate its extendability and clean and semantic code. YOOtheme has been known as a leading theme provider for over 10 years, and now with YOOtheme Pro they created the next page builder to be watched for on the WordPress market.

The Page Builder

If you are familiar with WordPress, YOOtheme Pro is a perfect choice for you since it is seamlessly integrated into the native WordPress customizer. You can easily create your layouts by dividing your content into sections, rows and grids. And thanks to the drag and drop interface, you can design beautiful responsive page layouts without even having to code. All your changes will be instantly shown in live preview.

Arrange Your Content With Ease

YOOtheme Pro has a growing library of over 30 content elements. Here you can find both common elements like the Video, Panel, Image or Heading, but you can also expect some advanced elements such as the Slider, Slideshow or Gallery with the masonry effect and filter option and even more. YOOtheme Pro also allows you to place WordPress widgets anywhere in your layout. All elements are built with the popular front-end framework UIkit that provides modern codebase with fast and sleek JavaScript.

Sophisticated Layouts for Your Website

YOOtheme invests a lot of time and effort into the development of their layouts. A team of professional designers regularly creates complete website concepts with a thought-out content structure and focus on modern design trends. They already have over 100 layouts with free-to-use images and even hand-made illustrations that can be found in the Layout Library. You can filter layouts according to topics and types, mix and match them, save your own layouts to reuse them later. This provides you with unlimited possibilities and makes creating websites in WordPress as easy as can be.

A Library of Over 70 Beautiful Styles

What makes YOOtheme Pro stand out even more is the Style Library that includes over 70 handcrafted styles. One click, and the look of your website changes completely. Whether you are looking for a minimalistic or a bold style, this substantial collection represents all trends. You can customize next to anything with YOOtheme Pro, from changing the style of each item separately to applying changes globally. This gives you all the power to style your WordPress website with none of the coding.

Integrated Unsplash Image Library

The popular Unsplash library that provides quality and free-to-use photos is seamlessly integrated into YOOtheme Pro. Due to this integration you can search through the library and try out images directly on your website without having to leave YOOtheme Pro. Use filter, browse through collections and users and insert images directly into your layouts. The images will only be downloaded after your click Save. This feature is a real time-saver for every designer.

Lightning-fast and Developer-friendly

YOOtheme Pro is a true piece of German engineering, it is fast, lightweight and easy like no other page builder. Powered by Vue.js and Uikit, it provides a great user experience. YOOtheme Pro also cares about speed. The small code size as well as the latest web technologies ensure the first meaningful paint gets quickly on the screen. And with auto-generated srcsets, lazy loading images and next-gen image formats like WebP YOOtheme Pro will boost the Google PageSpeed rank for your WordPress website. What’s more, Google Fonts are stored locally, which saves the request to Google and ensures GDPR compliance.

A modular and extendable architecture makes YOOtheme Pro extremely developer-friendly. It allows you to override everything, add custom elements, CSS, JavaScript and new themes settings. An extensive documentation including video tutorials and a section specifically written for developers will help you get started in no time.

Get YOOtheme Pro

YOOtheme Pro both simplifies and empowers website building. Regular release of theme packages including sophisticated layouts on a specific topic, six style variations and free-to-use images will make YOOtheme Pro the only thing you’ll need to create a website. And while we could talk more about how YOOtheme Pro supports WooCommerce and has a a Footer Builder and many desktop and mobile header layouts, we’d rather let you see for yourself. Get YOOtheme Pro and experience the future of website building today.

Direct Link to ArticlePermalink

The post Introducing the YOOtheme Pro Page Builder appeared first on CSS-Tricks.