1657974600
Nesta postagem do blog, vamos explorar as diferenças entre um HTML class
e um id
atributo! Desde como isso afeta o comportamento do navegador até dicas de estilo com CSS.
Primeiro vamos explorar o id
atributo e como podemos usá-lo, bem como quando usá-lo. Isso responde a muitas perguntas que os recém-chegados têm, como “Devo usar uma classe ou id em HTML?” e “Devo estilizar a classe ou id em CSS?”. Vamos descobrir!
Se você é novo em HTML, an id
é uma identidade única que você pode dar a um elemento HTML. Podemos usar quantos id
atributos quisermos, porém existem algumas regras sensatas:
id
por elementoid
atributos não podem ter o mesmo valor (é um HTML inválido ter IDs duplicados)Um id
cria um comportamento especial, você vai encontrá-los neste mesmo blog! Cada cabeçalho (como h3
usamos para que possamos incluir o id
valor como parte de um URL, que rolará automaticamente o usuário para essa parte da página da web ao carregar.
Imagine um post de blog que inclui um título “All About JavaScript Closures”, o título do blog gerado pode ser assim:
<h2 id="all-about-javascript-closures">
All About JavaScript Closures
</h2>
Nosso URL poderia então vincular automaticamente a essa parte do documento por meio do URL:
someblog.com/javascript-closures#all-about-javascript-closures
Você pode estilizar um id
através de um seletor CSS, curiosamente, usamos a mesma sintaxe da URL com um #
:
#all-about-javascript-closures {
background: red;
}
Só porque você pode, não significa que você deve. Eu recomendo evitar o estilo id
, pois é considerado único. A menos que haja um hack específico que você esteja planejando fazer, eu evitaria estilizar seus IDs, pois você está apenas limitando sua reutilização de CSS e, posteriormente, aumentando a folha de estilo.
Curiosamente, quaisquer id
propriedades tornam-se propriedades JavaScript no window
objeto global.
Então, se fizéssemos isso, na verdade criaríamos uma variável global com o mesmo nome:
<aside id="author">...</aside>
<script>
window.author; // <aside id="author"></aside>
</script>
Mas variáveis globais não são ótimas ou confiáveis, então realmente devemos evitá-las ao arquitetar nosso HTML.
É mais provável que, com seu JavaScript, seja melhor selecionar e alterar um class
- mas, se precisar, você sabe que o id
está lá.
Agora também existe uma classList
API que foi criada diretamente para trabalhar com seu class
atributo, então não há necessidade de usar uma id
na realidade.
A class
é a nossa maneira preferida de identificar elementos.
Depois de vincular a class
a um elemento, ele se torna segmentável por meio de CSS e JavaScript.
Devemos usar uma classe para fins de estilo e opcionalmente refletir o estado na árvore DOM (ou seja, para adicionar comportamento ou simplesmente um estilo estático).
A árvore DOM é uma representação ao vivo de nossa página HTML e é o que usamos com JavaScript. Por exemplo,
document.querySelector
é uma API DOM e não “JavaScript”.
As classes nos permitem especificar uma descrição para um estilo compartilhado, enquanto fornecem algum significado por trás do elemento:
<button class="btn">Small button</button>
<button class="btn">Medium button</button>
<button class="btn">Large button</button>
Poderíamos então usar .btn { background: blue }
em nossa folha de estilo para fornecer uma única regra de estilo para todos esses elementos! Ao contrário de um id
, podemos declarar a class
quantas vezes quisermos - para nos tornarmos o mais eficientes e reutilizáveis possível.
As classes também podem ser compostas, e podemos especificar várias classes por elemento , nos dando a capacidade de não apenas herdar um único estilo compartilhado, mas também fornecer uma adaptação, como pequeno, médio e grande, como abaixo:
<button class="btn btn--small">Small button</button>
<button class="btn btn--medium">Medium button</button>
<button class="btn btn--large">Large button</button>
Pode ser que esperemos usar a Metodologia BEM e fornecer uma classe modificadora, denotada com um --suffix
:
.btn--small { font-size: 12px }
.btn--medium { font-size: 14px }
.btn--large { font-size: 16px }
Nesse caso, o --small
descreveria uma versão modificada da base do .btn
. Tem sido minha metodologia CSS preferida por muitos anos.
🕵️♀️ Com a mudança para a arquitetura baseada em componentes com aplicativos da Web, prefiro o mínimo de estilos possível no meu
style.css
e procuraria fornecer um estilo por componente. Este é um padrão de arquitetura de componentes melhor, pois também fornece encapsulamento completo.
Com isso em mente, também devemos usar a para alterarclass
dinamicamente os valores relacionados ao estilo. Por exemplo, podemos ter uma classe que precisa ser adicionada ou removida com base em uma determinada condição. Como fazemos isso?'active'
Acontece que existe uma nova API embutida, que exigirá um polyfill para navegadores mais antigos , chamado classList
que está disponível para nós em cada Element
DOM Node.
Quando registramos .classList
nosso em um elemento, nos é retornado um DOMTokenList
para trabalharmos.
<button class="btn btn--small">Small button</button>
<script>
const button = document.querySelector('.btn .btn--small');
// ▶ DOMTokenList(2) ["btn", "btn--small", value: "btn btn--small"]
console.log(button.classList);
</script>
Você pode ver que classList
contém uma value
propriedade que reflete o class
valor da string atual.
Também se parece com um array, assim ["btn", "btn--small"]
como com elementos de array. É quase uma matriz, mas porque está fornecendo value
e outros classList
comportamentos no prototype
- é como uma matriz com comportamentos extras. Se você precisar usar os valores como uma matriz, poderá usar Array.from(button.classList)
.
O classList
recurso também vem com alguns ótimos prototype
métodos para adicionar/remover/alternar e muito mais com um class
:
<button class="btn btn--small">Small button</button>
<script>
const button = document.querySelector('.btn .btn--small');
// add + remove a class
button.classList.add('btn--large');
button.classList.remove('btn--small');
// toggle class on a click event
button.addEventListener('click', () => button.classList.toggle('btn--clicked'));
</script>
Também há muito mais na documentação classList que eu recomendo que você verifique também.
Nós cobrimos um monte de terreno neste artigo! Desde um simples elemento HTML id
ou class
até como isso afeta nossas variáveis globais em JavaScript e, finalmente, explorando APIs como classList
- e como elas se encaixam no ecossistema.
Resumindo, aqui está uma recapitulação do que aprendemos:
id
uma vez por páginaid
por elementoid
elementos de estilo, prefira umclass
id
atributo também cria uma propriedade JavaScript global emwindow
class
para fins de estilo e maximize classes que podem ser compostasclassList
API integrada para manipular classesid
pode ser considerado uma coisa do passado, a menos que queiramos usar alguns de seus recursosObrigado por ler!
1662107520
Superdom
You have dom
. It has all the DOM virtually within it. Use that power:
// Fetch all the page links
let links = dom.a.href;
// Links open in a new tab
dom.a.target = '_blank';
Only for modern browsers
Simply use the CDN via unpkg.com:
<script src="https://unpkg.com/superdom@1"></script>
Or use npm or bower:
npm|bower install superdom --save
It always returns an array with the matched elements. Get all the elements that match the selector:
// Simple element selector into an array
let allLinks = dom.a;
// Loop straight on the selection
dom.a.forEach(link => { ... });
// Combined selector
let importantLinks = dom['a.important'];
There are also some predetermined elements, such as id
, class
and attr
:
// Select HTML Elements by id:
let main = dom.id.main;
// by class:
let buttons = dom.class.button;
// or by attribute:
let targeted = dom.attr.target;
let targeted = dom.attr['target="_blank"'];
Use it as a function or a tagged template literal to generate DOM fragments:
// Not a typo; tagged template literals
let link = dom`<a href="https://google.com/">Google</a>`;
// It is the same as
let link = dom('<a href="https://google.com/">Google</a>');
Delete a piece of the DOM
// Delete all of the elements with the class .google
delete dom.class.google; // Is this an ad-block rule?
You can easily manipulate attributes right from the dom
node. There are some aliases that share the syntax of the attributes such as html
and text
(aliases for innerHTML
and textContent
). There are others that travel through the dom such as parent
(alias for parentNode) and children
. Finally, class
behaves differently as explained below.
The fetching will always return an array with the element for each of the matched nodes (or undefined if not there):
// Retrieve all the urls from the page
let urls = dom.a.href; // #attr-list
// ['https://google.com', 'https://facebook.com/', ...]
// Get an array of the h2 contents (alias of innerHTML)
let h2s = dom.h2.html; // #attr-alias
// ['Level 2 header', 'Another level 2 header', ...]
// Get whether any of the attributes has the value "_blank"
let hasBlank = dom.class.cta.target._blank; // #attr-value
// true/false
You also use these:
innerHTML
): retrieve a list of the htmlstextContent
): retrieve a list of the htmlsparentNode
): travel up one level// Set target="_blank" to all links
dom.a.target = '_blank'; // #attr-set
dom.class.tableofcontents.html = `
<ul class="tableofcontents">
${dom.h2.map(h2 => `
<li>
<a href="#${h2.id}">
${h2.innerHTML}
</a>
</li>
`).join('')}
</ul>
`;
To delete an attribute use the delete
keyword:
// Remove all urls from the page
delete dom.a.href;
// Remove all ids
delete dom.a.id;
It provides an easy way to manipulate the classes.
To retrieve whether a particular class is present or not:
// Get an array with true/false for a single class
let isTest = dom.a.class.test; // #class-one
For a general method to retrieve all classes you can do:
// Get a list of the classes of each matched element
let arrays = dom.a.class; // #class-arrays
// [['important'], ['button', 'cta'], ...]
// If you want a plain list with all of the classes:
let flatten = dom.a.class._flat; // #class-flat
// ['important', 'button', 'cta', ...]
// And if you just want an string with space-separated classes:
let text = dom.a.class._text; // #class-text
// 'important button cta ...'
// Add the class 'test' (different ways)
dom.a.class.test = true; // #class-make-true
dom.a.class = 'test'; // #class-push
// Remove the class 'test'
dom.a.class.test = false; // #class-make-false
Did we say it returns a simple array?
dom.a.forEach(link => link.innerHTML = 'I am a link');
But what an interesting array it is; indeed we are also proxy'ing it so you can manipulate its sub-elements straight from the selector:
// Replace all of the link's html with 'I am a link'
dom.a.html = 'I am a link';
Of course we might want to manipulate them dynamically depending on the current value. Just pass it a function:
// Append ' ^_^' to all of the links in the page
dom.a.html = html => html + ' ^_^';
// Same as this:
dom.a.forEach(link => link.innerHTML = link.innerHTML + ' ^_^');
Note: this won't work
dom.a.html += ' ^_^';
for more than 1 match (for reasons)
Or get into genetics to manipulate the attributes:
dom.a.attr.target = '_blank';
// Only to external sites:
let isOwnPage = el => /^https?\:\/\/mypage\.com/.test(el.getAttribute('href'));
dom.a.attr.target = (prev, i, element) => isOwnPage(element) ? '' : '_blank';
You can also handle and trigger events:
// Handle click events for all <a>
dom.a.on.click = e => ...;
// Trigger click event for all <a>
dom.a.trigger.click;
We are using Jest as a Grunt task for testing. Install Jest and run in the terminal:
grunt watch
Author: franciscop
Source Code: https://github.com/franciscop/superdom
License: MIT license
1667279100
Jekyll
plugin for Astronauts.
Spaceship is a minimalistic, powerful and extremely customizable Jekyll plugin. It combines everything you may need for convenient work, without unnecessary complications, like a real spaceship.
💡 Tip: I hope you enjoy using this plugin. If you like this project, a little star for it is your way make a clear statement: My work is valued. I would appreciate your support! Thank you!
Add jekyll-spaceship plugin in your site's Gemfile
, and run bundle install
.
# If you have any plugins, put them here!
group :jekyll_plugins do
gem 'jekyll-spaceship'
end
Or you better like to write in one line:
gem 'jekyll-spaceship', group: :jekyll_plugins
Add jekyll-spaceship to the plugins:
section in your site's _config.yml
.
plugins:
- jekyll-spaceship
💡 Tip: Note that GitHub Pages runs in safe
mode and only allows a set of whitelisted plugins. To use the gem in GitHub Pages, you need to build locally or use CI (e.g. travis, github workflow) and deploy to your gh-pages
branch.
This plugin runs with the following configuration options by default. Alternative settings for these options can be explicitly specified in the configuration file _config.yml
.
# Where things are
jekyll-spaceship:
# default enabled processors
processors:
- table-processor
- mathjax-processor
- plantuml-processor
- mermaid-processor
- polyfill-processor
- media-processor
- emoji-processor
- element-processor
mathjax-processor:
src:
- https://polyfill.io/v3/polyfill.min.js?features=es6
- https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js
config:
tex:
inlineMath:
- ['$','$']
- ['\(','\)']
displayMath:
- ['$$','$$']
- ['\[','\]']
svg:
fontCache: 'global'
optimize: # optimization on building stage to check and add mathjax scripts
enabled: true # value `false` for adding to all pages
include: [] # include patterns for math expressions checking (regexp)
exclude: [] # exclude patterns for math expressions checking (regexp)
plantuml-processor:
mode: default # mode value 'pre-fetch' for fetching image at building stage
css:
class: plantuml
syntax:
code: 'plantuml!'
custom: ['@startuml', '@enduml']
src: http://www.plantuml.com/plantuml/svg/
mermaid-processor:
mode: default # mode value 'pre-fetch' for fetching image at building stage
css:
class: mermaid
syntax:
code: 'mermaid!'
custom: ['@startmermaid', '@endmermaid']
config:
theme: default
src: https://mermaid.ink/svg/
media-processor:
default:
id: 'media-{id}'
class: 'media'
width: '100%'
height: 350
frameborder: 0
style: 'max-width: 600px; outline: none;'
allow: 'encrypted-media; picture-in-picture'
emoji-processor:
css:
class: emoji
src: https://github.githubassets.com/images/icons/emoji/
For now, these extended features are provided:
Noted that GitHub filters out style property, so the example displays with the obsolete align property. But in actual this plugin outputs style property with text-align CSS attribute.
^^ in a cell indicates it should be merged with the cell above.
This feature is contributed by pmccloghrylaing.
| Stage | Direct Products | ATP Yields |
| -----------------: | --------------: | ---------: |
| Glycolysis | 2 ATP ||
| ^^ | 2 NADH | 3--5 ATP |
| Pyruvaye oxidation | 2 NADH | 5 ATP |
| Citric acid cycle | 2 ATP ||
| ^^ | 6 NADH | 15 ATP |
| ^^ | 2 FADH | 3 ATP |
| 30--32 ATP |||
Code above would be parsed as:
Stage | Direct Products | ATP Yields |
---|---|---|
Glycolysis | 2 ATP | |
2 NADH | 3–5 ATP | |
Pyruvaye oxidation | 2 NADH | 5 ATP |
Citric acid cycle | 2 ATP | |
6 NADH | 15 ATP | |
2 FADH2 | 3 ATP | |
30–32 ATP |
A backslash at end to join cell contents with the following lines.
This feature is contributed by Lucas-C.
| : Easy Multiline : |||
| :----- | :----- | :------ |
| Apple | Banana | Orange \
| Apple | Banana | Orange \
| Apple | Banana | Orange
| Apple | Banana | Orange \
| Apple | Banana | Orange |
| Apple | Banana | Orange |
Code above would be parsed as:
Easy Multiline | ||
---|---|---|
Apple Apple Apple | Banana Banana Banana | Orange Orange Orange |
Apple Apple | Banana Banana | Orange Orange |
Apple | Banana | Orange |
Table header can be eliminated.
|--|--|--|--|--|--|--|--|
|♜| |♝|♛|♚|♝|♞|♜|
| |♟|♟|♟| |♟|♟|♟|
|♟| |♞| | | | | |
| |♗| | |♟| | | |
| | | | |♙| | | |
| | | | | |♘| | |
|♙|♙|♙|♙| |♙|♙|♙|
|♖|♘|♗|♕|♔| | |♖|
Code above would be parsed as:
♜ | ♝ | ♛ | ♚ | ♝ | ♞ | ♜ | |
♟ | ♟ | ♟ | ♟ | ♟ | ♟ | ||
♟ | ♞ | ||||||
♗ | ♟ | ||||||
♙ | |||||||
♘ | |||||||
♙ | ♙ | ♙ | ♙ | ♙ | ♙ | ♙ | |
♖ | ♘ | ♗ | ♕ | ♔ | ♖ |
Markdown table syntax use colons ":" for forcing column alignment.
Therefore, here we also use it for forcing cell alignment.
Table cell can be set alignment separately.
| : Fruits \|\| Food : |||
| :--------- | :-------- | :-------- |
| Apple | : Apple : | Apple \
| Banana | Banana | Banana \
| Orange | Orange | Orange |
| : Rowspan is 4 : || How's it? |
|^^ A. Peach || 1. Fine :|
|^^ B. Orange ||^^ 2. Bad |
|^^ C. Banana || It's OK! |
Code above would be parsed as:
Fruits || Food | ||
---|---|---|
Apple Banana Orange | Apple Banana Orange | Apple Banana Orange |
Rowspan is 4 A. Peach B. Orange C. Banana | ||
How's it? | ||
1. Fine 2. Bad | ||
It' OK! |
Sometimes we may need some abundant content (e.g., mathjax, image, video) in Markdown table
Therefore, here we also make markown syntax possible inside a cell.
| : MathJax \|\| Image : |||
| :------------ | :-------- | :----------------------------- |
| Apple | : Apple : | Apple \
| Banana | Banana | Banana \
| Orange | Orange | Orange |
| : Rowspan is 4 : || : How's it? : |
| ^^ A. Peach || 1. ![example][cell-image] |
| ^^ B. Orange || ^^ 2. $I = \int \rho R^{2} dV$ |
| ^^ C. Banana || **It's OK!** |
[cell-image]: https://jekyllrb.com/img/octojekyll.png "An exemplary image"
Code above would be parsed as:
MathJax || Image | ||
---|---|---|
Apple Banana Orange | Apple Banana Orange | Apple Banana Orange |
Rowspan is 4 A. Peach B. Orange C. Banana | ||
How's it? | ||
It' OK! |
This feature is very useful for custom cell such as using inline style. (e.g., background, color, font)
The idea and syntax comes from the Maruku package.
Following are some examples of attributes definitions (ALDs) and afterwards comes the syntax explanation:
{:ref-name: #id .cls1 .cls2}
{:second: ref-name #id-of-other title="hallo you"}
{:other: ref-name second}
An ALD line has the following structure:
If there is more than one ALD with the same reference name, the attribute definitions of all the ALDs are processed like they are defined in one ALD.
An inline attribute list (IAL) is used to attach attributes to another element.
Here are some examples for span IALs:
{: #id .cls1 .cls2} <!-- #id <=> id="id", .cls1 .cls2 <=> class="cls1 cls2" -->
{: ref-name title="hallo you"}
{: ref-name class='.cls3' .cls4}
Here is an example for custom table cell with IAL:
{:color-style: style="background: black;"}
{:color-style: style="color: white;"}
{:text-style: style="font-weight: 800; text-decoration: underline;"}
|: Here's an Inline Attribute Lists example :||||
| ------- | ------------------ | -------------------- | ------------------ |
|: :|: <div style="color: red;"> < Normal HTML Block > </div> :|||
| ^^ | Red {: .cls style="background: orange" } |||
| ^^ IALs | Green {: #id style="background: green; color: white" } |||
| ^^ | Blue {: style="background: blue; color: white" } |||
| ^^ | Black {: color-style text-style } |||
Code above would be parsed as:
Additionally, here you can learn more details about IALs.
MathJax is an open-source JavaScript display engine for LaTeX, MathML, and AsciiMath notation that works in all modern browsers.
Some of the main features of MathJax include:
At building stage, the MathJax engine script will be added by automatically checking whether there is a math expression in the page, this feature can help you improve the page performance on loading speed.
Put your math expression within $...$
$ a * b = c ^ b $
$ 2^{\frac{n-1}{3}} $
$ \int\_a^b f(x)\,dx. $
Code above would be parsed as:
PlantUML is a component that allows to quickly write:
There are two ways to create a diagram in your Jekyll blog page:
```plantuml!
Bob -> Alice : hello world
```
or
@startuml
Bob -> Alice : hello
@enduml
Code above would be parsed as:
Mermaid is a Javascript based diagramming and charting tool. It generates diagrams flowcharts and more, using markdown-inspired text for ease and speed.
It allows to quickly write:
There are two ways to create a diagram in your Jekyll blog page:
```mermaid!
pie title Pets adopted by volunteers
"Dogs" : 386
"Cats" : 85
"Rats" : 35
```
or
@startmermaid
pie title Pets adopted by volunteers
"Dogs" : 386
"Cats" : 85
"Rats" : 35
@endmermaid
Code above would be parsed as:
How often did you find yourself googling "How to embed a video/audio in markdown?"
While its not possible to embed a video/audio in markdown, the best and easiest way is to extract a frame from the video/audio. To add videos/audios to your markdown files easier I developped this tool for you, and it will parse the video/audio link inside the image block automatically.
For now, these media links parsing are provided:
There are two ways to embed a video/audio in your Jekyll blog page:
Inline-style:

Reference-style:
![][{reference}]
[{reference}]: {media-link}
For configuring media attributes (e.g, width, height), just adding query string to the link as below:
















As markdown is not only a lightweight markup language with plain-text-formatting syntax, but also an easy-to-read and easy-to-write plain text format, so writing a hybrid HTML with markdown is an awesome choice.
It's easy to write markdown inside HTML:
<script type="text/markdown">
# Hybrid HTML with Markdown is a not bad choice ^\_^
## Table Usage
| : Fruits \|\| Food : |||
| :--------- | :-------- | :-------- |
| Apple | : Apple : | Apple \
| Banana | Banana | Banana \
| Orange | Orange | Orange |
| : Rowspan is 4 : || How's it? |
|^^ A. Peach || 1. Fine :|
|^^ B. Orange ||^^ 2. Bad |
|^^ C. Banana || It's OK! |
## PlantUML Usage
@startuml
Bob -> Alice : hello
@enduml
## Video Usage

</script>
It allows us to polyfill features for extending markdown syntax.
For now, these polyfill features are provided:
A backslash at begin to escape the ordered list.
Normal:
1. List item Apple.
3. List item Banana.
10. List item Cafe.
Escaped:
\1. List item Apple.
\3. List item Banana.
\10. List item Cafe.
Code above would be parsed as:
Normal:
1. List item Apple.
2. List item Banana.
3. List item Cafe.
Escaped:
1. List item Apple.
3. List item Banana.
10. List item Cafe.
GitHub-flavored emoji images and names would allow emojifying content such as: it's raining :cat:s and :dog:s!
Noted that emoji images are served from the GitHub.com CDN, with a base URL of https://github.githubassets.com, which results in emoji image URLs like https://github.githubassets.com/images/icons/emoji/unicode/1f604.png.
In any page or post, use emoji as you would normally, e.g.
I give this plugin two :+1:!
Code above would be parsed as:
I give this plugin two :+1:!
If you'd like to serve emoji images locally, or use a custom emoji source, you can specify so in your _config.yml
file:
jekyll-spaceship:
emoji-processor:
src: "/assets/images/emoji"
See the Gemoji documentation for generating image files.
It allows us to modify elements via CSS3 selectors
. Through it you can easily modify the attributes of an element tag, replace the children nodes and so on, it's very flexible, but here is example usage for modifying a document:
# Here is a comprehensive example
jekyll-spaceship:
element-processor:
css:
- a: '<h1>Test</h1>' # Replace all `a` tags (String Style)
- ['a.link1', 'a.link2']: # Replace all `a.link1`, `a.link2` tags (Hash Style)
name: img # Replace element tag name
props: # Replace element properties
title: Good image # Add a title attribute
src: ['(^.*$)', '\0?a=123'] # Add query string to src attribute by regex pattern
style: # Add style attribute (Hash Style)
color: red
font-size: '1.2em'
children: # Add children to the element
- # First empty for adding after the last child node
- "<span>Google</span>" # First child node (String Style)
- # Middle empty for wrapping the children nodes
- name: span # Second child node (Hash Style)
props:
prop1: "1" # Custom property1
prop2: "2" # Custom property2
prop3: "3" # Custom property3
children: # Add nested chidren nodes
- "<span>Jekyll</span>" # First child node (String Style)
- name: span # Second child node (Hash Style)
props: # Add attributes to child node (Hash Style)
prop1: "a"
prop2: "b"
prop3: "c"
children: "<b>Yap!</b>" # Add children nodes (String Style)
- # Last empty for adding before the first child node
- a.link: '<a href="//t.com">Link</a>' # Replace all `a.link` tags (String Style)
- 'h1#title': # Replace `h1#title` tags (Hash Style)
children: I'm a title! # Replace inner html to new text
Automatically adds a target="_blank" rel="noopener noreferrer"
attribute to all external links in Jekyll's content.
jekyll-spaceship:
element-processor:
css:
- a: # Replace all `a` tags
props:
class: ['(^.*$)', '\0 ext-link'] # Add `ext-link` to class by regex pattern
target: _blank # Replace `target` value to `_blank`
rel: noopener noreferrer # Replace `rel` value to `noopener noreferrer`
Automatically adds loading="lazy"
to img
and iframe
tags to natively load lazily. Browser support is growing. If a browser does not support the loading
attribute, it will load the resource just like it would normally.
jekyll-spaceship:
element-processor:
css:
- a: # Replace all `a` tags
props: #
loading: lazy # Replace `loading` value to `lazy`
In case you want to prevent loading some images/iframes lazily, add loading="eager"
to their tags. This might be useful to prevent flickering of images during navigation (e.g. the site's logo).
See the following examples to prevent lazy loading.
jekyll-spaceship:
element-processor:
css:
- a: # Replace all `a` tags
props: #
loading: eager # Replace `loading` value to `eager`
There are three options when using this method to lazy load images. Here are the supported values for the loading attribute:
Issues and Pull Requests are greatly appreciated. If you've never contributed to an open source project before I'm more than happy to walk you through how to create a pull request.
You can start by opening an issue describing the problem that you're looking to resolve and we'll go from there.
Author: jeffreytse
Source Code: https://github.com/jeffreytse/jekyll-spaceship
License: MIT license
1657974600
Nesta postagem do blog, vamos explorar as diferenças entre um HTML class
e um id
atributo! Desde como isso afeta o comportamento do navegador até dicas de estilo com CSS.
Primeiro vamos explorar o id
atributo e como podemos usá-lo, bem como quando usá-lo. Isso responde a muitas perguntas que os recém-chegados têm, como “Devo usar uma classe ou id em HTML?” e “Devo estilizar a classe ou id em CSS?”. Vamos descobrir!
Se você é novo em HTML, an id
é uma identidade única que você pode dar a um elemento HTML. Podemos usar quantos id
atributos quisermos, porém existem algumas regras sensatas:
id
por elementoid
atributos não podem ter o mesmo valor (é um HTML inválido ter IDs duplicados)Um id
cria um comportamento especial, você vai encontrá-los neste mesmo blog! Cada cabeçalho (como h3
usamos para que possamos incluir o id
valor como parte de um URL, que rolará automaticamente o usuário para essa parte da página da web ao carregar.
Imagine um post de blog que inclui um título “All About JavaScript Closures”, o título do blog gerado pode ser assim:
<h2 id="all-about-javascript-closures">
All About JavaScript Closures
</h2>
Nosso URL poderia então vincular automaticamente a essa parte do documento por meio do URL:
someblog.com/javascript-closures#all-about-javascript-closures
Você pode estilizar um id
através de um seletor CSS, curiosamente, usamos a mesma sintaxe da URL com um #
:
#all-about-javascript-closures {
background: red;
}
Só porque você pode, não significa que você deve. Eu recomendo evitar o estilo id
, pois é considerado único. A menos que haja um hack específico que você esteja planejando fazer, eu evitaria estilizar seus IDs, pois você está apenas limitando sua reutilização de CSS e, posteriormente, aumentando a folha de estilo.
Curiosamente, quaisquer id
propriedades tornam-se propriedades JavaScript no window
objeto global.
Então, se fizéssemos isso, na verdade criaríamos uma variável global com o mesmo nome:
<aside id="author">...</aside>
<script>
window.author; // <aside id="author"></aside>
</script>
Mas variáveis globais não são ótimas ou confiáveis, então realmente devemos evitá-las ao arquitetar nosso HTML.
É mais provável que, com seu JavaScript, seja melhor selecionar e alterar um class
- mas, se precisar, você sabe que o id
está lá.
Agora também existe uma classList
API que foi criada diretamente para trabalhar com seu class
atributo, então não há necessidade de usar uma id
na realidade.
A class
é a nossa maneira preferida de identificar elementos.
Depois de vincular a class
a um elemento, ele se torna segmentável por meio de CSS e JavaScript.
Devemos usar uma classe para fins de estilo e opcionalmente refletir o estado na árvore DOM (ou seja, para adicionar comportamento ou simplesmente um estilo estático).
A árvore DOM é uma representação ao vivo de nossa página HTML e é o que usamos com JavaScript. Por exemplo,
document.querySelector
é uma API DOM e não “JavaScript”.
As classes nos permitem especificar uma descrição para um estilo compartilhado, enquanto fornecem algum significado por trás do elemento:
<button class="btn">Small button</button>
<button class="btn">Medium button</button>
<button class="btn">Large button</button>
Poderíamos então usar .btn { background: blue }
em nossa folha de estilo para fornecer uma única regra de estilo para todos esses elementos! Ao contrário de um id
, podemos declarar a class
quantas vezes quisermos - para nos tornarmos o mais eficientes e reutilizáveis possível.
As classes também podem ser compostas, e podemos especificar várias classes por elemento , nos dando a capacidade de não apenas herdar um único estilo compartilhado, mas também fornecer uma adaptação, como pequeno, médio e grande, como abaixo:
<button class="btn btn--small">Small button</button>
<button class="btn btn--medium">Medium button</button>
<button class="btn btn--large">Large button</button>
Pode ser que esperemos usar a Metodologia BEM e fornecer uma classe modificadora, denotada com um --suffix
:
.btn--small { font-size: 12px }
.btn--medium { font-size: 14px }
.btn--large { font-size: 16px }
Nesse caso, o --small
descreveria uma versão modificada da base do .btn
. Tem sido minha metodologia CSS preferida por muitos anos.
🕵️♀️ Com a mudança para a arquitetura baseada em componentes com aplicativos da Web, prefiro o mínimo de estilos possível no meu
style.css
e procuraria fornecer um estilo por componente. Este é um padrão de arquitetura de componentes melhor, pois também fornece encapsulamento completo.
Com isso em mente, também devemos usar a para alterarclass
dinamicamente os valores relacionados ao estilo. Por exemplo, podemos ter uma classe que precisa ser adicionada ou removida com base em uma determinada condição. Como fazemos isso?'active'
Acontece que existe uma nova API embutida, que exigirá um polyfill para navegadores mais antigos , chamado classList
que está disponível para nós em cada Element
DOM Node.
Quando registramos .classList
nosso em um elemento, nos é retornado um DOMTokenList
para trabalharmos.
<button class="btn btn--small">Small button</button>
<script>
const button = document.querySelector('.btn .btn--small');
// ▶ DOMTokenList(2) ["btn", "btn--small", value: "btn btn--small"]
console.log(button.classList);
</script>
Você pode ver que classList
contém uma value
propriedade que reflete o class
valor da string atual.
Também se parece com um array, assim ["btn", "btn--small"]
como com elementos de array. É quase uma matriz, mas porque está fornecendo value
e outros classList
comportamentos no prototype
- é como uma matriz com comportamentos extras. Se você precisar usar os valores como uma matriz, poderá usar Array.from(button.classList)
.
O classList
recurso também vem com alguns ótimos prototype
métodos para adicionar/remover/alternar e muito mais com um class
:
<button class="btn btn--small">Small button</button>
<script>
const button = document.querySelector('.btn .btn--small');
// add + remove a class
button.classList.add('btn--large');
button.classList.remove('btn--small');
// toggle class on a click event
button.addEventListener('click', () => button.classList.toggle('btn--clicked'));
</script>
Também há muito mais na documentação classList que eu recomendo que você verifique também.
Nós cobrimos um monte de terreno neste artigo! Desde um simples elemento HTML id
ou class
até como isso afeta nossas variáveis globais em JavaScript e, finalmente, explorando APIs como classList
- e como elas se encaixam no ecossistema.
Resumindo, aqui está uma recapitulação do que aprendemos:
id
uma vez por páginaid
por elementoid
elementos de estilo, prefira umclass
id
atributo também cria uma propriedade JavaScript global emwindow
class
para fins de estilo e maximize classes que podem ser compostasclassList
API integrada para manipular classesid
pode ser considerado uma coisa do passado, a menos que queiramos usar alguns de seus recursosObrigado por ler!
1595318322
HTML stands for a hypertext markup language. For the designs to be displayed in web browser HTML is the markup language. Technologies like Cascading style sheets (CSS) and scripting languages such as JavaScript assist HTML. With the help of HTML websites and the web, designs are created. Html has a wide range of academic applications. HTML has a series of elements. HTML helps to display web content. Its elements tell the web how to display the contents.
The document component of HTML is known as an HTML element. HTML element helps in displaying the web pages. An HTML document is a mixture of text nodes and HTML elements.
The simple fundamental components oh HTML is
HTML helps in creating web pages. In web pages, there are texts, pictures, colouring schemes, tables, and a variety of other things. HTML allows all these on a web page.
There are a lot of attributes in HTML. It may get difficult to memorize these attributes. HTML is a tricky concept. Sometimes it gets difficult to find a single mistake that doesn’t let the web page function properly.
Many minor things are to be kept in mind in HTML. To complete an HTML assignment, it is always advisable to seek help from online experts. These experts are well trained and acknowledged with the subject. They provide quality content within the prescribed deadline. With several positive reviews, the online expert help for HTML assignment is highly recommended.
#html assignment help #html assignment writing help #online html assignment writing help #html assignment help service online #what is html #about html
1617789060
The prospect of learning HTML can seem confusing at first: where to begin, what to learn, the best ways to learn — it can be difficult to get started. In this article, we’ll explore the best ways for learning HTML to assist you on your programming journey.
Hypertext Markup Language (HTML) is the standard markup language for documents meant to be displayed in a web browser. Along with Cascading Style Sheets (CSS) and JavaScript, HTML completes the trio of essential tools used in creating modern web documents.
HTML provides the structure of a webpage, from the header and footer sections to paragraphs of text, videos, and images. CSS allows you to set the visual properties of different HTML elements, like changing colors, setting the order of blocks on the screen, and defining which elements to display. JavaScript automates changes to HTML and CSS, for example, making the font larger in a paragraph when a user clicks a button on the page.
#html #html-css #html-fundamentals #learning-html #html-css-basics #html-templates