Mike  Kozey

Mike Kozey

1660366980

VXG_playersdk: Flutter Plugin to Use The VXG Player SDK

VXG Player SDK for Flutter

A Flutter plugin to use the VXG Player SDK, which enables playback of media files and streams for your apps.

To learn more about VXG Player SDK, please visit the VXG Player SDK website

Installing

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add vxg_playersdk

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  vxg_playersdk: ^0.0.2

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:vxg_playersdk/playersdk.dart';
import 'package:vxg_playersdk/playersdkcommon.dart';
import 'package:vxg_playersdk/playersdkconfig.dart';

example/lib/main.dart

import 'package:flutter/material.dart';
import 'player.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    PlayerView player = new PlayerView();

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Container(
        child: player,
      ),
    );
  }
}

Getting Started

To get started with VXG Player SDK, please see the documentation.

Usage

To use this plugin, please visit the Core Usage documentation

Issues and feedback

Please file VXG Player SDK for Flutter specific issues, bugs, or feature requests in our issue tracker.

Plugin issues that are not specific to Flutterfire can be filed in the Flutter issue tracker.

Download Details:

Author: VideoExpertsGroup
Source Code: https://github.com/VideoExpertsGroup/VXG.Media.SDK.Flutter/ 
License: BSD-3-Clause license

#flutter #dart #sdk #media 

VXG_playersdk: Flutter Plugin to Use The VXG Player SDK
Royce  Reinger

Royce Reinger

1658899080

MediaWiki API: A Library for interacting with MediaWiki API From Ruby

MediaWiki API

A library for interacting with MediaWiki API from Ruby. Uses adapter-agnostic Faraday gem to talk to the API.

Installation

Add this line to your application's Gemfile:

gem "mediawiki_api"

And then execute:

$ bundle

Or install it yourself as:

$ gem install mediawiki_api

Usage

Assuming you have MediaWiki installed via MediaWiki-Vagrant.

require "mediawiki_api"

client = MediawikiApi::Client.new "http://127.0.0.1:8080/w/api.php"
client.log_in "username", "password" # default Vagrant username and password are "Admin", "vagrant"
client.create_account "username", "password" # will not work on wikis that require CAPTCHA, like Wikipedia
client.create_page "title", "content"
client.get_wikitext "title"
client.protect_page "title", "reason", "protections" #  protections are optional, default is "edit=sysop|move=sysop"
client.delete_page "title", "reason"
client.upload_image "filename", "path", "comment", "ignorewarnings"
client.watch_page "title"
client.unwatch_page "title"
client.meta :siteinfo, siprop: "extensions"
client.prop :info, titles: "Some page"
client.query titles: ["Some page", "Some other page"]

Advanced Usage

Any API action can be requested using #action. See the MediaWiki API documentation for supported actions and parameters.

By default, the client will attempt to get a csrf token before attempting the action. For actions that do not require a token, you can specify token_type: false to avoid requesting the unnecessary token before the real request. For example:

client.action :parse, page: 'Main Page', token_type: false

Links

MediaWiki API gem at: Gerrit, GitHub, RubyGems, Code Climate.

Contributing

See https://www.mediawiki.org/wiki/Gerrit

Release notes

0.7.1 2017-01-31

  • Add text param to MediawikiApi::Client#upload_image

0.7.0 2016-08-03

  • Automatically follow redirects for all API requests.

0.6.0 2016-05-25

  • Update account creation code for AuthManager. This change updates the gem to test which API flavor is in use, then send requests accordingly.

0.5.0 2015-09-04

  • Client cookies can now be read and modified via MediawikiApi::Client#cookies.
  • Logging in will recurse upon a NeedToken API error only once to avoid infinite recursion in cases where authentication is repeatedly unsuccessful.

0.4.1 2015-06-17

  • Allow for response-less ApiError exceptions to make mocking in tests easier

0.4.0 2015-06-16

  • Use action=query&meta=tokens to fetch tokens, instead of deprecated action=tokens

0.3.1 2015-01-06

  • Actions now automatically refresh token and re-submit action if first attempt returns 'badtoken'.

0.3.0 2014-10-14

  • HTTP 400 and 500 responses now result in an HttpError exception.
  • Edit failures now result in an EditError exception.

0.2.1 2014-08-26

  • Fix error handling for token requests

0.2.0 2014-08-06

  • Automatic response parsing.
  • Handling of API error responses.
  • Watch/unwatch support.
  • Query support.
  • Public MediawikiApi::Client#action method for advanced API use.

0.1.4 2014-07-18

  • Added MediawikiApi::Client#protect_page.
  • Updated documentation.

0.1.3 2014-06-28

  • Added MediawikiApi::Client#upload_image.

0.1.2 2014-04-11

  • Added MediawikiApi::Client#get_wikitext.

0.1.1 2014-04-01

  • Updated documentation.

0.1.0 2014-03-13

  • Complete refactoring.
  • Removed MediawikiApi#create_article, #create_user and #delete_article.
  • Added MediawikiApi::Client#new, #log_in, #create_page, #delete_page, #create_account.
  • Added unit tests.

0.0.2 2014-02-11

  • Added MediawikiApi#delete_article.

0.0.1 2014-02-07

  • Added MediawikiApi#create_article and #create_user.

Author: Wikimedia
Source Code: https://github.com/wikimedia/mediawiki-ruby-api 
License: View license

#ruby #api #media 

MediaWiki API: A Library for interacting with MediaWiki API From Ruby
Thierry  Perret

Thierry Perret

1656367200

Comment Choisir Entre Media Queries Et Container Queries

Tous ceux qui se tiennent au courant des derniers événements dans le monde de la conception réactive conviendront que l'introduction des requêtes de conteneur CSS change la donne. C'est la chose la plus excitante qui soit arrivée depuis l'introduction, eh bien, des requêtes des médias.

Mais qu'est-ce qu'une requête de conteneur ? Pourquoi les requêtes de conteneur sont-elles importantes et comment pouvez-vous les utiliser ?

Dans cet article, nous allons répondre à toutes ces questions et plus encore à travers les sections suivantes :

  • Qu'est-ce qu'une requête média en CSS ?
  • Le problème des requêtes média
  • Quand et comment utiliser les media queries
  • Quand et comment utiliser les requêtes de conteneur

Sans perdre plus de temps, allons-y.

Qu'est-ce qu'une requête média en CSS ?

Il y a longtemps, la plupart des sites Web avaient beaucoup de mal à rendre les composants sur différentes tailles d'écran, en particulier avec la révolution des téléphones mobiles. La plupart des sites Web ont résolu ce problème en créant un nouveau site Web avec le domaine m.. Si vous avez déjà utilisé m.facebook.com, voici pourquoi.

Tout cela était avant les requêtes des médias. Avec les requêtes multimédias, les sites Web peuvent être conçus pour s'adapter à une fenêtre d'affichage particulière. Il est donc révolu le temps de zoomer sur votre smartphone pour voir ce qu'il y a sur le site Web.

Les requêtes multimédias fournissent une instruction conditionnelle autour de certains styles, qui sont ensuite implémentés ou non selon que les conditions sont remplies ou non.

Le problème des requêtes média

Bien que les requêtes médias aient beaucoup changé, elles avaient toujours un problème : elles ne sont pas réutilisables. Avec les requêtes multimédias, vous pouvez créer un élément réactif et l'implémenter, et même s'il a l'air bien dans un cas d'utilisation standard, il ne fonctionnera probablement pas aussi bien s'il est déplacé vers un autre conteneur avec des propriétés CSS qui affectent les dimensions de l'élément. Pour que cela fonctionne correctement, vous devrez ajouter de nombreuses autres propriétés CSS.

C'est là qu'interviennent les requêtes de conteneur. Avec les requêtes de conteneur, vous pouvez désormais cibler des éléments individuels eux-mêmes et leur permettre de s'adapter à pratiquement n'importe quel conteneur ou mise en page donné.

Les requêtes de conteneur sont comme les requêtes multimédia ; la seule différence est qu'ils rendent un conteneur ou un élément réactif en fonction de l'espace disponible pour le conteneur, plutôt que de la fenêtre d'affichage. Mais cela soulève la question : avons-nous encore besoin des requêtes des médias ?

 

Quand et comment utiliser les media queries

La réponse à la question ci-dessus est oui ! Il existe encore une tonne de cas d'utilisation pour les requêtes multimédias, bien que les requêtes de conteneur résolvent leurs limitations considérables.

Les requêtes multimédias peuvent et doivent toujours être utilisées pour les mises en page, qui sont généralement au niveau le plus élevé du DOM et non imbriquées dans un autre conteneur. Ils sont les mieux adaptés pour cela car la mise en page principale ne doit pas s'adapter à autre chose que la fenêtre d'affichage.

Les requêtes multimédias peuvent également être utilisées pour styliser des éléments globaux tels que l'espacement, la taille de la police ou les couleurs. Par exemple, si vous créez un site Web avec de grandes tailles de police, il est probable que la police et l'espacement seront trop grands pour un écran mobile. Cela peut être résolu avec des requêtes multimédias comme celle-ci :

:root {
   --font-size-hl: 20px;
   --font-size-h2: 15px;
   --font-size-h3: 12px;
   --font-size-p: 8px;


   --letter-spacing: 8px;
}

@media (min-width: 300px) {
   :root {
       --font-size-hl: 13px;
       --font-size-h2: 10;
       --font-size-h3: 8px;
       --font-size-p: 5pxrem;

       --letter spacing: 4px;
   }
}

L'un des scénarios de requêtes multimédias dans lequel briller est lorsque vous devez supprimer un composant d'une page. Par exemple, regardez cette page d'accueil Instagram :

Affichage du bureau du flux Instagram et de la barre de messages

Sur le bureau, la barre de message est vraiment belle, mais la plupart des appareils mobiles n'ont pas la taille d'écran pour l'afficher correctement. Avec les requêtes multimédias, l'onglet de message entier peut être supprimé et la même page s'affichera comme ceci.

La vue mobile d'Instagram masque la barre de message

Il convient de noter que les requêtes multimédias ne servent pas uniquement à détecter les tailles d'écran et leur impact sur les composants.

Les requêtes multimédias peuvent également être utilisées pour différentes requêtes liées aux préférences de l'utilisateur, telles que :

Quand et comment utiliser les requêtes de conteneur

Les requêtes de conteneur vous permettent de cibler un conteneur spécifique et de le configurer pour qu'il s'affiche en fonction de la largeur et de la hauteur du conteneur, sans avoir à utiliser des requêtes multimédias. Il est principalement utilisé pour les composants de carte, mais il est flexible, vous pouvez donc l'utiliser pour plusieurs composants.

Avec CSS vanilla, les propriétés utilisées dans les requêtes de conteneur partagent de nombreuses similitudes avec les propriétés que vous avez utilisées dans les requêtes multimédias. Les seules autres propriétés que vous devez apprendre sont :

  • container-type: utilisé pour déclarer l'élément en tant que conteneur de requête, permettant au composant enfant d'interroger celui-ci
  • container-name: Utilisé pour attribuer un nom au conteneur pour un filtrage ultérieur

Jetons un coup d'œil à un exemple de carte rapide. Tout d'abord, rédigeons une carte avec HTML.

<div class="container">
  <div class="contain-container contain-container--small">
    <h2>first example</h2>
    <div class="contain">
      <div class="contain__thumbnail"&gt;</div>
      <div class="contain__content">

        <h3 class="contain__title">Lorem Ipsium in english</h3>
        <p class="contain__description">But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. .</p>
      </div>
    </div>
  </div>
  <div class="contain-container contain-container--large">
    <h2>Second example</h2>
    <div class="contain">
      <div class="contain__thumbnail"></div>
      <div class="contain__content">
        <h3 class="contain__title">Lorem Ipsium in english</h3>
        <p class="contain__description">To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure.</p>
      </div>
    </div>
  </div>
</div>

Le texte factice n'est qu'une version traduite de lorem ipsum. C'est ma bizarrerie personnelle.

Ensuite, insérons le CSS.

body {
  background: #5f64e2;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica,
    Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  color: #fdf2f2;
}

.container {
  padding: 16px;
  margin: auto;
  display: flex;
  gap: 16px;
}

.contain-container {
  margin: 16px auto;
  flex-grow: 0;
  contain: layout inline-size;
  container-type: inline-size;
  --css-contain: layout inline-size;
}

.contain-container--small {
  width: 300px;
}

.contain-container--large {
  width: 600px;
}

.contain {
  padding: 16px;
  border-radius: 8px;
  background: black;
  margin-bottom: 16px;
  color: white;
}

  .contain__thumbnail {
    height: 130px;
    min-width: 130px;
    background: red;
    border-radius: 4px;
  }

  .contain__title {
    margin-top: 4px;
    margin-bottom: 8px;
  }

  .contain__description {
    margin: 0;
  }

Le résultat du code ci-dessus ressemblera à ceci :

Deux cartes de requête de conteneur

Les deux cartes sont en grande partie identiques, sauf que l'une a une largeur de 300 pixels et l'autre une largeur de 600 pixels. Avec les requêtes de conteneur, nous pouvons donner à la carte de droite un aspect et un comportement très différents avec le code suivant.

@container (min-width: 400px) {
  .contain {
    background-color: white;
    color: black;
    display: flex;
    gap: 16px;
  }
}

Ce que fait ce code, c'est dire à tout conteneur de plus de 400 pixels de large d'avoir une couleur d'arrière-plan blanche, d'utiliser display: flex, et d'avoir une couleur de texte noire. Le résultat ressemblera à ceci :

Cartes de requête mises à jour

Les modifications apportées à la carte de droite ne s'appliquent que si la carte doit occuper un espace d'une largeur ≥ 400px, donc s'il n'y a pas assez d'espace pour l'afficher, ou si elle est visualisée par un appareil mobile, les cartes reviendront pour ça.

Cartes de requête de conteneur en vue mobile

Requêtes de conteneur avec CSS-in-JS

Je sais que JSS, ou CSS-in-JS , est un sujet assez controversé en ce moment. Il y a quelques personnes, comme ce gars qui déteste JSS et ne veut pas que vous vous en approchiez, ou ce gars qui l'adore et veut que vous l'utilisiez.

Que vous aimiez JSS ou non, vous devez admettre que c'est assez pratique. Tout comme avec le CSS normal, il est possible d'utiliser des requêtes de conteneur dans JSS. Voici un exemple très simple de la façon dont cela fonctionne.

Tout d'abord, construisons quatre conteneurs simples.

<div class=cquery>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? </h1>
</div>

<div class=cquery style=width:80%>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it?</h1>
</div>

<div class=cquery style=width:60%>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it?</h1>
</div>

<div class=cquery style=width:40%>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it?</h1>
</div>

Ensuite, ajoutons le JSS. J'ai mis quelques commentaires pour que ce soit facilement compréhensible.

function JSinCSS() {
  //target an html element with id ='JSinCSS' and declare it tag
  let tag = document.querySelector("#JSinCSS");

  //if there is no html element with id ='#JSinCSS'
  if (!tag) {
    //create a style tag like this
    //<style></style>
    tag = document.createElement("style");

    //set id of style tag to be 'JSinCSS'
    //<style id='JSinCSS'></style>
    tag.id = "JSinCSS";
    //we call document.head.appendChild to append the style element to the head tag as a child.
    document.head.appendChild(tag);
  }

  //inside the style tag add innerHTML to it

  tag.innerHTML = `

    body:before {
      content: '${innerWidth} x ${innerHeight}';
    }

    .cquery {
      border: 4px solid red;
      background-color: green;
    }

    ${containerQuery('.cquery', 'this.offsetWidth > 500', `

      $this {
        background: blue;
      }

      $this h1 {
        font-size: 30pt;
      }

    `)}

    ${containerQuery('.cquery', 'this.offsetWidth > 800', `

      $this {
        background: purple;
      }

      $this h1 {
        font-size: 30pt;
      }

    `)}


    ${containerQuery('.cquery', 'this.offsetWidth > 1000', `

      $this {
        background: gold;
      }

      $this h1 {
        font-size: 30pt;
      }

    `)}

  `

}

function containerQuery(selector, test, stylesheet) {
    //target the container element and declare it tag
  var tag = document.querySelectorAll(selector);
  var style = "";
  var count = 1;

  for (var i = 0; i < tag.length; i++) {
      //tag.length return the number of nodes in tag
      // run a forLoop so when i == tag.length 
      //declare a function that returns test
    var func = new Function(`return ${test}`);
    var attr = (selector + test).replace(/[= "'><+\.]/g, "");

    if (func.call(tag[i])) {
      tag[i].setAttribute(`data-${attr}`, count);

      var css = stylesheet.replace(/\$this/g, `[data-${attr}="${count}"]`);

      style += css;

      count++;
    } else {
      tag[i].setAttribute(`data-${attr}`, "");
    }
  }

  return style;
}

//call the function in to listen to different events and call the function JSinCSS
window.addEventListener("load", JSinCSS);
window.addEventListener("resize", JSinCSS);
window.addEventListener("input", JSinCSS);
window.addEventListener("click", JSinCSS);

Le code ci-dessus crée quatre conteneurs différents, puis définit une requête de conteneur avec la containerQuerybalise afin que les couleurs des conteneurs changent à différentes tailles. Le résultat ressemble à ceci.

Quatre cartes de requête de conteneur en jaune, violet, bleu et vert

À partir du code HTML, vous pouvez voir qu'il s'agit du même conteneur. Mais à une largeur de ≥1000px, la couleur du conteneur devient or. À des largeurs de 800px et 500px, le conteneur devient respectivement violet et bleu. En dessous, il reste dans sa couleur verte par défaut. Ainsi, si ces mêmes conteneurs doivent occuper un espace ≤ 1 000 px, vous obtiendrez ceci :

Les conteneurs deviennent bleu violet et vert dans un espace plus petit

Voici le lien CodePen si vous voulez jouer un peu avec le code.

Conclusion

L'intérêt de la conception réactive est d'atteindre la polyvalence et l'efficacité, et avec l'introduction des requêtes de conteneurs, nous nous rapprochons un peu plus de la perfection en matière de conception réactive. Il résout une grande partie des limitations des requêtes multimédias, mais il ne remplace pas entièrement les requêtes multimédias.

Personnellement, je pense que les requêtes de médias et les requêtes de conteneurs sont comme des pépites de poulet et de la sauce piquante : elles ont toutes deux leurs utilisations séparément, mais ensemble, elles feront basculer votre monde. J'espère que vous vous amuserez à les utiliser.

Rendez-vous dans le prochain.

Source : https://blog.logrocket.com/choose-between-media-container-queries/

#media #css 

Comment Choisir Entre Media Queries Et Container Queries
Hong  Nhung

Hong Nhung

1656366000

Cách Chọn Giữa Truy Vấn Phương Tiện Và Truy Vấn Vùng Chứa Trong CSS

Tất cả những ai cập nhật các sự kiện mới nhất trong thế giới thiết kế đáp ứng sẽ đồng ý rằng việc giới thiệu các truy vấn vùng chứa CSS là một yếu tố thay đổi cuộc chơi. Đó là điều thú vị nhất đã xảy ra kể từ khi giới thiệu, tốt, các truy vấn phương tiện truyền thông.

Nhưng truy vấn vùng chứa là gì? Tại sao các truy vấn vùng chứa lại quan trọng và bạn có thể sử dụng chúng như thế nào?

Trong bài viết này, chúng tôi sẽ trả lời tất cả những câu hỏi đó và hơn thế nữa thông qua các phần sau:

  • Truy vấn phương tiện trong CSS là gì?
  • Vấn đề với các truy vấn phương tiện
  • Khi nào và cách sử dụng truy vấn phương tiện
  • Khi nào và cách sử dụng truy vấn vùng chứa

Không mất thời gian nữa, hãy bắt tay ngay vào.

Truy vấn phương tiện trong CSS là gì?

Từ lâu, hầu hết các trang web đã gặp rất nhiều khó khăn khi hiển thị các thành phần trên các kích thước màn hình khác nhau, đặc biệt là với cuộc cách mạng điện thoại di động. Hầu hết các trang web đã khắc phục sự cố đó bằng cách tạo một trang web mới với miền m.. Nếu bạn đã từng sử dụng m.facebook.com, đây là lý do tại sao.

Tất cả đó là trước khi truy vấn phương tiện truyền thông. Với các truy vấn phương tiện, các trang web có thể được xây dựng để phù hợp với một khung nhìn cụ thể, vì vậy không còn thời gian để phóng to điện thoại thông minh của bạn để xem nội dung trên trang web.

Truy vấn phương tiện cung cấp một câu lệnh điều kiện xung quanh một số kiểu, sau đó được triển khai hoặc không dựa trên việc các điều kiện có được đáp ứng hay không.

Vấn đề với các truy vấn phương tiện

Mặc dù các truy vấn phương tiện đã thay đổi rất nhiều, nhưng chúng vẫn có một vấn đề: chúng không thể sử dụng lại được. Với các truy vấn phương tiện, bạn có thể tạo một phần tử đáp ứng và triển khai nó, và mặc dù nó trông đẹp trong trường hợp sử dụng tiêu chuẩn, nó có thể sẽ không hoạt động tốt nếu nó được chuyển sang một vùng chứa khác có thuộc tính CSS ảnh hưởng đến kích thước phần tử. Để nó hoạt động bình thường, bạn sẽ cần thêm nhiều thuộc tính CSS khác.

Đây là nơi xuất hiện các truy vấn vùng chứa. Với các truy vấn vùng chứa, giờ đây bạn có thể tự nhắm mục tiêu các phần tử riêng lẻ và cho phép chúng thích ứng với hầu hết mọi vùng chứa hoặc bố cục nhất định.

Truy vấn vùng chứa giống như truy vấn phương tiện truyền thông; sự khác biệt duy nhất là chúng tạo ra một vùng chứa hoặc một phần tử đáp ứng dựa trên không gian có sẵn cho vùng chứa, thay vì chế độ xem. Nhưng điều đó đặt ra câu hỏi: Liệu chúng ta có cần đến các truy vấn phương tiện truyền thông nữa không?

 

Khi nào và cách sử dụng truy vấn phương tiện

Câu trả lời cho câu hỏi trên là có! Vẫn còn rất nhiều trường hợp sử dụng cho các truy vấn phương tiện, mặc dù các truy vấn container đã giải quyết được những hạn chế đáng kể của chúng.

Truy vấn phương tiện có thể và vẫn nên được sử dụng cho bố cục trang, thường nằm ở cấp cao nhất của DOM và không được lồng trong một vùng chứa khác. Chúng phù hợp nhất cho việc này vì bố cục trang chính không nên thích ứng với bất kỳ thứ gì khác ngoài chế độ xem.

Truy vấn phương tiện cũng có thể được sử dụng để tạo kiểu cho các phần tử toàn cục như khoảng cách, cỡ chữ hoặc màu sắc. Ví dụ: nếu bạn xây dựng một trang web với kích thước phông chữ lớn, rất có thể phông chữ và khoảng cách sẽ quá lớn đối với màn hình di động. Điều đó có thể được khắc phục bằng các truy vấn phương tiện như sau:

:root {
   --font-size-hl: 20px;
   --font-size-h2: 15px;
   --font-size-h3: 12px;
   --font-size-p: 8px;


   --letter-spacing: 8px;
}

@media (min-width: 300px) {
   :root {
       --font-size-hl: 13px;
       --font-size-h2: 10;
       --font-size-h3: 8px;
       --font-size-p: 5pxrem;

       --letter spacing: 4px;
   }
}

Một trong những tình huống truy vấn phương tiện truyền thông xuất hiện là khi bạn phải xóa một thành phần khỏi một trang. Ví dụ, hãy xem trang chủ Instagram này:

Trên máy tính để bàn, thanh thông báo trông thực sự tốt, nhưng hầu hết các thiết bị di động không có kích thước màn hình để hiển thị điều này một cách thích hợp. Với truy vấn phương tiện, toàn bộ tab tin nhắn có thể bị xóa và cùng một trang sẽ hiển thị như thế này.

Cần lưu ý rằng các truy vấn phương tiện không chỉ để phát hiện kích thước màn hình và cách chúng ảnh hưởng đến các thành phần.

Truy vấn phương tiện cũng có thể được sử dụng cho các truy vấn khác nhau liên quan đến sở thích của người dùng, chẳng hạn như:

Khi nào và cách sử dụng truy vấn vùng chứa

Truy vấn vùng chứa cho phép bạn nhắm mục tiêu một vùng chứa cụ thể và định cấu hình vùng chứa đó để hiển thị dựa trên chiều rộng và chiều cao của vùng chứa mà không cần phải sử dụng truy vấn phương tiện. Nó chủ yếu được sử dụng cho các thành phần thẻ, nhưng nó linh hoạt, vì vậy bạn có thể sử dụng nó cho nhiều thành phần.

Với vanilla CSS, các thuộc tính được sử dụng trong các truy vấn vùng chứa có rất nhiều điểm tương đồng với các thuộc tính mà bạn đang sử dụng trong các truy vấn phương tiện. Các thuộc tính duy nhất khác bạn cần tìm hiểu là:

  • container-type: Được sử dụng để khai báo phần tử như một vùng chứa truy vấn, cho phép thành phần con truy vấn nó
  • container-name: Được sử dụng để gán tên cho vùng chứa để lọc thêm

Hãy xem một ví dụ về thẻ nhanh. Đầu tiên, hãy soạn thảo một thẻ bằng HTML.

<div class="container">
  <div class="contain-container contain-container--small">
    <h2>first example</h2>
    <div class="contain">
      <div class="contain__thumbnail"&gt;</div>
      <div class="contain__content">

        <h3 class="contain__title">Lorem Ipsium in english</h3>
        <p class="contain__description">But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. .</p>
      </div>
    </div>
  </div>
  <div class="contain-container contain-container--large">
    <h2>Second example</h2>
    <div class="contain">
      <div class="contain__thumbnail"></div>
      <div class="contain__content">
        <h3 class="contain__title">Lorem Ipsium in english</h3>
        <p class="contain__description">To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure.</p>
      </div>
    </div>
  </div>
</div>

Văn bản giả chỉ là một phiên bản dịch của lorem ipsum. Đó là câu hỏi bâng quơ của cá nhân tôi.

Tiếp theo, hãy đặt CSS.

body {
  background: #5f64e2;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica,
    Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  color: #fdf2f2;
}

.container {
  padding: 16px;
  margin: auto;
  display: flex;
  gap: 16px;
}

.contain-container {
  margin: 16px auto;
  flex-grow: 0;
  contain: layout inline-size;
  container-type: inline-size;
  --css-contain: layout inline-size;
}

.contain-container--small {
  width: 300px;
}

.contain-container--large {
  width: 600px;
}

.contain {
  padding: 16px;
  border-radius: 8px;
  background: black;
  margin-bottom: 16px;
  color: white;
}

  .contain__thumbnail {
    height: 130px;
    min-width: 130px;
    background: red;
    border-radius: 4px;
  }

  .contain__title {
    margin-top: 4px;
    margin-bottom: 8px;
  }

  .contain__description {
    margin: 0;
  }

Kết quả của đoạn mã trên sẽ như thế này:

Hai thẻ truy vấn vùng chứa

Cả hai thẻ phần lớn đều giống nhau, ngoại trừ một thẻ có chiều rộng 300px và thẻ kia có chiều rộng 600px. Với các truy vấn vùng chứa, chúng ta có thể làm cho thẻ có giao diện phù hợp và hoạt động rất khác với mã sau.

@container (min-width: 400px) {
  .contain {
    background-color: white;
    color: black;
    display: flex;
    gap: 16px;
  }
}

Những gì mã đó làm là yêu cầu bất kỳ vùng chứa nào có chiều rộng trên 400px phải có màu nền là màu trắng, sử dụng display: flexvà có màu văn bản là màu đen. Kết quả sẽ như thế này:

Đã cập nhật thẻ truy vấn

Các thay đổi đối với thẻ ở bên phải chỉ áp dụng nếu thẻ phải chiếm không gian có chiều rộng ≥ 400px, vì vậy nếu không có đủ dung lượng để hiển thị hoặc nếu thẻ đang được thiết bị di động xem, thẻ sẽ hoàn nguyên đến điều này.

Thẻ truy vấn vùng chứa trong chế độ xem trên thiết bị di động

Truy vấn vùng chứa với CSS-in-JS

Tôi biết JSS, hoặc CSS-in-JS , là một chủ đề gây tranh cãi khá nhiều ngay bây giờ. Có một vài người, chẳng hạn như anh chàng này ghét JSS và không muốn bạn ở gần nó, hoặc anh chàng này hoàn toàn yêu thích nó và muốn bạn sử dụng nó.

Cho dù bạn có thích JSS hay không, bạn phải thừa nhận rằng nó khá tiện dụng. Cũng giống như với CSS thông thường, có thể sử dụng các truy vấn vùng chứa trong JSS. Đây là một ví dụ rất đơn giản về cách nó hoạt động.

Đầu tiên, hãy xây dựng bốn thùng chứa đơn giản.

<div class=cquery>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? </h1>
</div>

<div class=cquery style=width:80%>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it?</h1>
</div>

<div class=cquery style=width:60%>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it?</h1>
</div>

<div class=cquery style=width:40%>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it?</h1>
</div>

Tiếp theo, hãy thêm JSS. Tôi đã đưa một số nhận xét vào để làm cho nó dễ hiểu.

function JSinCSS() {
  //target an html element with id ='JSinCSS' and declare it tag
  let tag = document.querySelector("#JSinCSS");

  //if there is no html element with id ='#JSinCSS'
  if (!tag) {
    //create a style tag like this
    //<style></style>
    tag = document.createElement("style");

    //set id of style tag to be 'JSinCSS'
    //<style id='JSinCSS'></style>
    tag.id = "JSinCSS";
    //we call document.head.appendChild to append the style element to the head tag as a child.
    document.head.appendChild(tag);
  }

  //inside the style tag add innerHTML to it

  tag.innerHTML = `

    body:before {
      content: '${innerWidth} x ${innerHeight}';
    }

    .cquery {
      border: 4px solid red;
      background-color: green;
    }

    ${containerQuery('.cquery', 'this.offsetWidth > 500', `

      $this {
        background: blue;
      }

      $this h1 {
        font-size: 30pt;
      }

    `)}

    ${containerQuery('.cquery', 'this.offsetWidth > 800', `

      $this {
        background: purple;
      }

      $this h1 {
        font-size: 30pt;
      }

    `)}


    ${containerQuery('.cquery', 'this.offsetWidth > 1000', `

      $this {
        background: gold;
      }

      $this h1 {
        font-size: 30pt;
      }

    `)}

  `

}

function containerQuery(selector, test, stylesheet) {
    //target the container element and declare it tag
  var tag = document.querySelectorAll(selector);
  var style = "";
  var count = 1;

  for (var i = 0; i < tag.length; i++) {
      //tag.length return the number of nodes in tag
      // run a forLoop so when i == tag.length 
      //declare a function that returns test
    var func = new Function(`return ${test}`);
    var attr = (selector + test).replace(/[= "'><+\.]/g, "");

    if (func.call(tag[i])) {
      tag[i].setAttribute(`data-${attr}`, count);

      var css = stylesheet.replace(/\$this/g, `[data-${attr}="${count}"]`);

      style += css;

      count++;
    } else {
      tag[i].setAttribute(`data-${attr}`, "");
    }
  }

  return style;
}

//call the function in to listen to different events and call the function JSinCSS
window.addEventListener("load", JSinCSS);
window.addEventListener("resize", JSinCSS);
window.addEventListener("input", JSinCSS);
window.addEventListener("click", JSinCSS);

Đoạn mã trên tạo bốn vùng chứa khác nhau và sau đó đặt truy vấn vùng chứa với containerQuerythẻ để màu sắc của các vùng chứa thay đổi ở các kích thước khác nhau. Kết quả trông như thế này.

Bốn thẻ truy vấn vùng chứa màu vàng, tím, xanh lam và xanh lục

Từ HTML, bạn có thể thấy đó là cùng một vùng chứa. Nhưng ở độ rộng ≥1000px, màu vùng chứa sẽ trở thành vàng. Ở độ rộng 800px và 500px, vùng chứa sẽ trở thành màu tím và xanh lam tương ứng. Dưới đó, nó vẫn ở màu xanh lục mặc định. Vì vậy, nếu những vùng chứa tương tự này phải chiếm không gian ≤1000px, bạn sẽ nhận được điều này:

Các thùng chứa trở nên xanh tím và xanh lục trong không gian nhỏ hơn

Đây là liên kết CodePen nếu bạn muốn chơi với mã một chút.

Sự kết luận

Toàn bộ điểm của thiết kế đáp ứng là đạt được tính linh hoạt và hiệu quả, và với sự ra đời của các truy vấn vùng chứa, chúng tôi đã tiến gần hơn một bước đến sự hoàn hảo trong thiết kế đáp ứng. Nó giải quyết rất nhiều hạn chế của các truy vấn phương tiện, nhưng nó không hoàn toàn thay thế các truy vấn phương tiện.

Cá nhân tôi nghĩ rằng các truy vấn phương tiện truyền thông và truy vấn container giống như gà cốm và sốt nóng: cả hai đều có công dụng riêng biệt, nhưng cùng nhau, chúng sẽ khuấy động thế giới của bạn. Tôi hy vọng bạn vui vẻ khi sử dụng chúng.

Hẹn gặp lại các bạn trong những bài tiếp theo.

Nguồn: https://blog.logrocket.com/choose-between-media-container-queries/

#media #css 

Cách Chọn Giữa Truy Vấn Phương Tiện Và Truy Vấn Vùng Chứa Trong CSS

Elegir Entre Consultas De Medios Y Consultas De Contenedores

Todos los que se mantienen al día con los últimos eventos en el mundo del diseño receptivo estarán de acuerdo en que la introducción de consultas de contenedores CSS es un cambio de juego. Es lo más emocionante que ha sucedido desde la introducción de las consultas de medios.

Pero, ¿qué es una consulta de contenedor? ¿Por qué son importantes las consultas de contenedores y cómo puede usarlas?

En este artículo, vamos a responder todas esas preguntas y más a través de las siguientes secciones:

  • ¿Qué es una consulta de medios en CSS?
  • El problema con las consultas de medios
  • Cuándo y cómo usar consultas de medios
  • Cuándo y cómo usar consultas de contenedor

Sin perder más tiempo, entremos de lleno.

¿Qué es una consulta de medios en CSS?

Hace mucho tiempo, la mayoría de los sitios web tenían muchos problemas para representar componentes en diferentes tamaños de pantalla, especialmente con la revolución de los teléfonos móviles. La mayoría de los sitios web solucionaron ese problema creando un nuevo sitio web con el dominio m.. Si alguna vez has usado m.facebook.com, esta es la razón.

Todo eso fue antes de las consultas de los medios. Con las consultas de medios, los sitios web se pueden crear para que se ajusten a una ventana de visualización en particular, por lo que se acabaron los días de hacer zoom en su teléfono inteligente para ver qué hay en el sitio web.

Las consultas de medios proporcionan una declaración condicional en torno a algunos estilos, que luego se implementan o no en función de si se cumplen o no las condiciones.

El problema con las consultas de medios

Si bien las consultas de medios cambiaron mucho, todavía tenían un problema: no son reutilizables. Con las consultas de medios, puede crear un elemento receptivo e implementarlo, y aunque se ve bien en un caso de uso estándar, probablemente no funcionará tan bien si se mueve a un contenedor diferente con propiedades CSS que afectan las dimensiones del elemento. Para que funcione correctamente, deberá agregar muchas más propiedades CSS.

Aquí es donde entran en juego las consultas de contenedores. Con las consultas de contenedores, ahora puede dirigirse a elementos individuales y habilitarlos para que se adapten a prácticamente cualquier contenedor o diseño dado.

Las consultas de contenedores son como las consultas de medios; la única diferencia es que hacen que un contenedor o elemento responda según el espacio disponible para el contenedor, en lugar de la ventana gráfica. Pero eso plantea la pregunta: ¿necesitamos más las consultas de los medios?

 

Cuándo y cómo usar consultas de medios

La respuesta a la pregunta anterior es ¡sí! Todavía hay un montón de casos de uso para consultas de medios, a pesar de que las consultas de contenedores resuelven sus limitaciones considerables.

Las consultas de medios pueden y deben seguir usándose para diseños de página, que generalmente se encuentran en el nivel más alto del DOM y no están anidados en otro contenedor. Son los más adecuados para esto porque el diseño de la página principal no debe adaptarse a nada más que a la ventana gráfica.

Las consultas de medios también se pueden usar para diseñar elementos globales como el espaciado, el tamaño de fuente o los colores. Por ejemplo, si crea un sitio web con fuentes de gran tamaño, es probable que la fuente y el espacio sean demasiado grandes para una pantalla móvil. Eso se puede arreglar con consultas de medios como esta:

:root {
   --font-size-hl: 20px;
   --font-size-h2: 15px;
   --font-size-h3: 12px;
   --font-size-p: 8px;


   --letter-spacing: 8px;
}

@media (min-width: 300px) {
   :root {
       --font-size-hl: 13px;
       --font-size-h2: 10;
       --font-size-h3: 8px;
       --font-size-p: 5pxrem;

       --letter spacing: 4px;
   }
}

Uno de los escenarios de consultas de medios en los que brilla es cuando tienes que eliminar un componente de una página. Por ejemplo, mira esta página de inicio de Instagram:

En el escritorio, la barra de mensajes se ve muy bien, pero la mayoría de los dispositivos móviles no tienen el tamaño de pantalla para mostrar esto de manera adecuada. Con las consultas de medios, se puede eliminar toda la pestaña del mensaje y la misma página se mostrará así.

Vale la pena señalar que las consultas de medios no son solo para detectar tamaños de pantalla y cómo afectan los componentes.

Las consultas de medios también se pueden usar para diferentes consultas relacionadas con las preferencias del usuario, como:

Cuándo y cómo usar consultas de contenedor

Las consultas de contenedores le permiten dirigirse a un contenedor específico y configurarlo para que se muestre según el ancho y la altura del contenedor, sin tener que usar consultas de medios. Se usa principalmente para componentes de tarjetas, pero es flexible, por lo que puede usarlo para múltiples componentes.

Con Vanilla CSS, las propiedades utilizadas en las consultas de contenedores comparten muchas similitudes con las propiedades que ha estado utilizando en las consultas de medios. Las únicas otras propiedades que necesita aprender son:

  • container-type: se usa para declarar el elemento como un contenedor de consultas, lo que permite que el componente secundario consulte contra él
  • container-name: Se utiliza para asignar un nombre al contenedor para un mayor filtrado.

Echemos un vistazo a un ejemplo de tarjeta rápida. Primero, hagamos un borrador de una tarjeta con HTML.

<div class="container">
  <div class="contain-container contain-container--small">
    <h2>first example</h2>
    <div class="contain">
      <div class="contain__thumbnail"&gt;</div>
      <div class="contain__content">

        <h3 class="contain__title">Lorem Ipsium in english</h3>
        <p class="contain__description">But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. .</p>
      </div>
    </div>
  </div>
  <div class="contain-container contain-container--large">
    <h2>Second example</h2>
    <div class="contain">
      <div class="contain__thumbnail"></div>
      <div class="contain__content">
        <h3 class="contain__title">Lorem Ipsium in english</h3>
        <p class="contain__description">To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure.</p>
      </div>
    </div>
  </div>
</div>

El texto ficticio es solo una versión traducida de lorem ipsum. Es mi peculiaridad personal.

A continuación, introduzcamos el CSS.

body {
  background: #5f64e2;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica,
    Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  color: #fdf2f2;
}

.container {
  padding: 16px;
  margin: auto;
  display: flex;
  gap: 16px;
}

.contain-container {
  margin: 16px auto;
  flex-grow: 0;
  contain: layout inline-size;
  container-type: inline-size;
  --css-contain: layout inline-size;
}

.contain-container--small {
  width: 300px;
}

.contain-container--large {
  width: 600px;
}

.contain {
  padding: 16px;
  border-radius: 8px;
  background: black;
  margin-bottom: 16px;
  color: white;
}

  .contain__thumbnail {
    height: 130px;
    min-width: 130px;
    background: red;
    border-radius: 4px;
  }

  .contain__title {
    margin-top: 4px;
    margin-bottom: 8px;
  }

  .contain__description {
    margin: 0;
  }

El resultado del código anterior se verá así:

Ambas tarjetas son prácticamente iguales, excepto que una tiene un ancho de 300 px y la otra tiene un ancho de 600 px. Con las consultas de contenedor, podemos hacer que la tarjeta de la derecha se vea y se comporte de manera muy diferente con el siguiente código.

@container (min-width: 400px) {
  .contain {
    background-color: white;
    color: black;
    display: flex;
    gap: 16px;
  }
}

Lo que hace ese código es decirle a cualquier contenedor que tenga más de 400 px de ancho que tenga un color de fondo blanco, use display: flexy tenga un color de texto negro. El resultado se verá así:

Los cambios en la tarjeta de la derecha solo se aplican si la tarjeta tiene que ocupar un espacio con un ancho de ≥ 400 px, por lo que si no hay suficiente espacio para que se muestre, o si está siendo vista por un dispositivo móvil, las tarjetas se revertirán. a esto.

Consultas de contenedores con CSS-in-JS

Sé que JSS, o CSS-in-JS , es un tema bastante controvertido en este momento. Hay un par de personas, como este tipo que odia JSS y no quiere que te acerques a él, o este tipo que lo ama absolutamente y quiere que lo uses.

Ya sea que te guste JSS o no, debes admitir que es bastante útil. Al igual que con CSS normal, es posible usar consultas de contenedores en JSS. He aquí un ejemplo muy simple de cómo funciona.

Primero, construyamos cuatro contenedores simples.

<div class=cquery>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? </h1>
</div>

<div class=cquery style=width:80%>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it?</h1>
</div>

<div class=cquery style=width:60%>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it?</h1>
</div>

<div class=cquery style=width:40%>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it?</h1>
</div>

A continuación, agreguemos el JSS. He puesto algunos comentarios para que sea fácilmente comprensible.

function JSinCSS() {
  //target an html element with id ='JSinCSS' and declare it tag
  let tag = document.querySelector("#JSinCSS");

  //if there is no html element with id ='#JSinCSS'
  if (!tag) {
    //create a style tag like this
    //<style></style>
    tag = document.createElement("style");

    //set id of style tag to be 'JSinCSS'
    //<style id='JSinCSS'></style>
    tag.id = "JSinCSS";
    //we call document.head.appendChild to append the style element to the head tag as a child.
    document.head.appendChild(tag);
  }

  //inside the style tag add innerHTML to it

  tag.innerHTML = `

    body:before {
      content: '${innerWidth} x ${innerHeight}';
    }

    .cquery {
      border: 4px solid red;
      background-color: green;
    }

    ${containerQuery('.cquery', 'this.offsetWidth > 500', `

      $this {
        background: blue;
      }

      $this h1 {
        font-size: 30pt;
      }

    `)}

    ${containerQuery('.cquery', 'this.offsetWidth > 800', `

      $this {
        background: purple;
      }

      $this h1 {
        font-size: 30pt;
      }

    `)}


    ${containerQuery('.cquery', 'this.offsetWidth > 1000', `

      $this {
        background: gold;
      }

      $this h1 {
        font-size: 30pt;
      }

    `)}

  `

}

function containerQuery(selector, test, stylesheet) {
    //target the container element and declare it tag
  var tag = document.querySelectorAll(selector);
  var style = "";
  var count = 1;

  for (var i = 0; i < tag.length; i++) {
      //tag.length return the number of nodes in tag
      // run a forLoop so when i == tag.length 
      //declare a function that returns test
    var func = new Function(`return ${test}`);
    var attr = (selector + test).replace(/[= "'><+\.]/g, "");

    if (func.call(tag[i])) {
      tag[i].setAttribute(`data-${attr}`, count);

      var css = stylesheet.replace(/\$this/g, `[data-${attr}="${count}"]`);

      style += css;

      count++;
    } else {
      tag[i].setAttribute(`data-${attr}`, "");
    }
  }

  return style;
}

//call the function in to listen to different events and call the function JSinCSS
window.addEventListener("load", JSinCSS);
window.addEventListener("resize", JSinCSS);
window.addEventListener("input", JSinCSS);
window.addEventListener("click", JSinCSS);

El código anterior crea cuatro contenedores diferentes y luego establece una consulta de contenedor con la containerQueryetiqueta para que los colores de los contenedores cambien en diferentes tamaños. El resultado se ve así.

Desde el HTML, puede ver que es el mismo contenedor. Pero con un ancho de ≥1000px, el color del contenedor se vuelve dorado. Con anchos de 800 px y 500 px, el contenedor se vuelve morado y azul, respectivamente. Debajo de eso, permanece en su color verde predeterminado. Entonces, si estos mismos contenedores tienen que ocupar un espacio de ≤1000px, obtendrás esto:

Aquí está el enlace CodePen si quieres jugar un poco con el código.

Conclusión

El objetivo principal del diseño receptivo es lograr versatilidad y eficiencia, y con la introducción de consultas de contenedores, estamos un paso más cerca de la perfección en el diseño receptivo. Resuelve muchas de las limitaciones de las consultas de medios, pero no las reemplaza por completo.

Personalmente, creo que las consultas de medios y las consultas de contenedores son como nuggets de pollo y salsa picante: ambas tienen sus usos por separado, pero juntas harán temblar tu mundo. Espero que te diviertas usándolos.

Nos vemos en la próxima.

Fuente: https://blog.logrocket.com/choose- between -media-container-queries/

#media #css 

 Elegir Entre Consultas De Medios Y Consultas De Contenedores
曾 俊

曾 俊

1656363600

如何在媒体查询和容器查询之间进行选择

每个跟上响应式设计世界最新事件的人都会同意 CSS 容器查询的引入是一个游戏规则的改变者。这是自从引入媒体查询以来发生的最令人兴奋的事情。

但什么是容器查询?为什么容器查询很重要以及如何使用它们?

在本文中,我们将通过以下部分回答所有这些问题以及更多问题:

  • CSS 中的媒体查询是什么?
  • 媒体查询的问题
  • 何时以及如何使用媒体查询
  • 何时以及如何使用容器查询

不再浪费时间,让我们开始吧。

CSS 中的媒体查询是什么?

很久以前,大多数网站在不同的屏幕尺寸上渲染组件时都会遇到很多麻烦,尤其是在手机革命的情况下。大多数网站通过使用该域创建一个新网站来解决这个问题m.。如果您曾经使用过m.facebook.com,这就是原因。

所有这些都是在媒体查询之前。通过媒体查询,可以构建网站以适应特定的视口,因此放大智能手机以查看网站内容的日子已经一去不复返了。

媒体查询提供围绕某些样式的条件语句,然后根据条件是否满足来实现或不实现。

媒体查询的问题

尽管媒体查询发生了很大变化,但它们仍然存在一个问题:它们不可重用。使用媒体查询,您可以创建一个响应式元素并实现它,即使它在标准用例中看起来不错,但如果将其移动到具有影响元素尺寸的 CSS 属性的不同容器中,它可能就无法正常工作。要使其正常工作,您需要添加更多 CSS 属性。

这就是容器查询的用武之地。通过容器查询,您现在可以定位各个元素本身,并使它们能够适应几乎任何给定的容器或布局。

容器查询类似于媒体查询;唯一的区别是它们根据容器可用的空间而不是视口使容器或元素响应。但这提出了一个问题:我们还需要媒体查询吗?

 

何时以及如何使用媒体查询

上述问题的答案是肯定的!尽管容器查询解决了它们相当大的局限性,但媒体查询仍有大量用例。

媒体查询可以而且应该仍然用于页面布局,它们通常位于 DOM 的最顶层,而不是嵌套在另一个容器中。它们最适合这个,因为主页布局不应该适应视口以外的任何东西。

媒体查询也可用于设置全局元素的样式,如间距、字体大小或颜色。例如,如果您构建一个字体较大的网站,则字体和间距可能对于移动屏幕来说太大了。这可以通过这样的媒体查询来解决:

:root {
   --font-size-hl: 20px;
   --font-size-h2: 15px;
   --font-size-h3: 12px;
   --font-size-p: 8px;


   --letter-spacing: 8px;
}

@media (min-width: 300px) {
   :root {
       --font-size-hl: 13px;
       --font-size-h2: 10;
       --font-size-h3: 8px;
       --font-size-p: 5pxrem;

       --letter spacing: 4px;
   }
}

当您必须从页面中删除组件时,其中一种场景媒体查询会大放异彩。例如,看看这个 Instagram 主页:

Instagram 提要和消息栏的桌面视图

在桌面上,消息栏看起来非常好,但大多数移动设备的屏幕尺寸无法正确显示。使用媒体查询,可以删除整个消息选项卡,并且相同的页面将像这样显示。

Instagram 移动视图隐藏消息栏

值得注意的是,媒体查询不仅仅用于检测屏幕尺寸以及它们如何影响组件。

媒体查询也可用于与用户偏好相关的不同查询,例如:

何时以及如何使用容器查询

容器查询允许您定位特定容器并将其配置为根据容器的宽度和高度显示,而无需使用媒体查询。它主要用于卡片组件,但它很灵活,因此您可以将它用于多个组件。

使用 vanilla CSS,容器查询中使用的属性与您在媒体查询中使用的属性有很多相似之处。您需要学习的唯一其他属性是:

  • container-type:用于将元素声明为查询容器,允许子组件对其进行查询
  • container-name:用于为容器分配名称以进行进一步过滤

让我们看一个快速卡片示例。首先,让我们用 HTML 起草一张卡片。

<div class="container">
  <div class="contain-container contain-container--small">
    <h2>first example</h2>
    <div class="contain">
      <div class="contain__thumbnail"&gt;</div>
      <div class="contain__content">

        <h3 class="contain__title">Lorem Ipsium in english</h3>
        <p class="contain__description">But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. .</p>
      </div>
    </div>
  </div>
  <div class="contain-container contain-container--large">
    <h2>Second example</h2>
    <div class="contain">
      <div class="contain__thumbnail"></div>
      <div class="contain__content">
        <h3 class="contain__title">Lorem Ipsium in english</h3>
        <p class="contain__description">To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure.</p>
      </div>
    </div>
  </div>
</div>

虚拟文本只是 lorem ipsum 的翻译版本。这是我个人的怪癖。

接下来,让我们放入 CSS。

body {
  background: #5f64e2;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica,
    Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  color: #fdf2f2;
}

.container {
  padding: 16px;
  margin: auto;
  display: flex;
  gap: 16px;
}

.contain-container {
  margin: 16px auto;
  flex-grow: 0;
  contain: layout inline-size;
  container-type: inline-size;
  --css-contain: layout inline-size;
}

.contain-container--small {
  width: 300px;
}

.contain-container--large {
  width: 600px;
}

.contain {
  padding: 16px;
  border-radius: 8px;
  background: black;
  margin-bottom: 16px;
  color: white;
}

  .contain__thumbnail {
    height: 130px;
    min-width: 130px;
    background: red;
    border-radius: 4px;
  }

  .contain__title {
    margin-top: 4px;
    margin-bottom: 8px;
  }

  .contain__description {
    margin: 0;
  }

上述代码的结果将如下所示:

两张集装箱查询卡

两张卡片基本相同,只是一张宽度为 300 像素,另一张宽度为 600 像素。使用容器查询,我们可以使用以下代码使正确的卡片看起来和行为非常不同。

@container (min-width: 400px) {
  .contain {
    background-color: white;
    color: black;
    display: flex;
    gap: 16px;
  }
}

该代码的作用是告诉任何超过 400px 宽的容器具有白色背景色、 usedisplay: flex和黑色文本颜色。结果将如下所示:

更新的查询卡

右侧卡片的更改仅适用于卡片必须占用宽度≥ 400px 的空间,因此如果没有足够的空间显示,或者正在通过移动设备查看,卡片将还原对此。

移动视图中的容器查询卡

使用 CSS-in-JS 进行容器查询

我知道 JSS 或CSS-in-JS现在是一个颇具争议的话题。有几个人,比如这个讨厌 JSS 并且不想让你靠近它的人,或者这个绝对喜欢它并希望你使用它的人。

无论您是否喜欢JSS,您都必须承认它非常方便。就像使用普通 CSS 一样,可以在 JSS 中使用容器查询。这是一个非常简单的例子,说明它是如何工作的。

首先,让我们构建四个简单的容器。

<div class=cquery>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? </h1>
</div>

<div class=cquery style=width:80%>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it?</h1>
</div>

<div class=cquery style=width:60%>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it?</h1>
</div>

<div class=cquery style=width:40%>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it?</h1>
</div>

接下来,让我们添加 JSS。为了便于理解,我添加了一些注释。

function JSinCSS() {
  //target an html element with id ='JSinCSS' and declare it tag
  let tag = document.querySelector("#JSinCSS");

  //if there is no html element with id ='#JSinCSS'
  if (!tag) {
    //create a style tag like this
    //<style></style>
    tag = document.createElement("style");

    //set id of style tag to be 'JSinCSS'
    //<style id='JSinCSS'></style>
    tag.id = "JSinCSS";
    //we call document.head.appendChild to append the style element to the head tag as a child.
    document.head.appendChild(tag);
  }

  //inside the style tag add innerHTML to it

  tag.innerHTML = `

    body:before {
      content: '${innerWidth} x ${innerHeight}';
    }

    .cquery {
      border: 4px solid red;
      background-color: green;
    }

    ${containerQuery('.cquery', 'this.offsetWidth > 500', `

      $this {
        background: blue;
      }

      $this h1 {
        font-size: 30pt;
      }

    `)}

    ${containerQuery('.cquery', 'this.offsetWidth > 800', `

      $this {
        background: purple;
      }

      $this h1 {
        font-size: 30pt;
      }

    `)}


    ${containerQuery('.cquery', 'this.offsetWidth > 1000', `

      $this {
        background: gold;
      }

      $this h1 {
        font-size: 30pt;
      }

    `)}

  `

}

function containerQuery(selector, test, stylesheet) {
    //target the container element and declare it tag
  var tag = document.querySelectorAll(selector);
  var style = "";
  var count = 1;

  for (var i = 0; i < tag.length; i++) {
      //tag.length return the number of nodes in tag
      // run a forLoop so when i == tag.length 
      //declare a function that returns test
    var func = new Function(`return ${test}`);
    var attr = (selector + test).replace(/[= "'><+\.]/g, "");

    if (func.call(tag[i])) {
      tag[i].setAttribute(`data-${attr}`, count);

      var css = stylesheet.replace(/\$this/g, `[data-${attr}="${count}"]`);

      style += css;

      count++;
    } else {
      tag[i].setAttribute(`data-${attr}`, "");
    }
  }

  return style;
}

//call the function in to listen to different events and call the function JSinCSS
window.addEventListener("load", JSinCSS);
window.addEventListener("resize", JSinCSS);
window.addEventListener("input", JSinCSS);
window.addEventListener("click", JSinCSS);

上面的代码创建了四个不同的容器,然后使用containerQuery标签设置容器查询,以便容器的颜色以不同的大小变化。结果看起来像这样。

黄色、紫色、蓝色和绿色四种容器查询卡

从 HTML 中,您可以看到它是同一个容器。但在宽度≥1000px 时,容器颜色变为金色。在宽度为 800px 和 500px 时,容器分别变为紫色和蓝色。在此之下,它保持默认的绿色。因此,如果这些相同的容器必须占用≤1000px 的空间,您将得到:

容器在更小的空间内变成紫蓝色和绿色

这是CodePen 链接,如果您想稍微玩一下代码。

结论

响应式设计的重点是实现多功能性和效率,随着容器查询的引入,我们离完美的响应式设计又近了一步。它解决了媒体查询的很多限制,但并不能完全取代媒体查询。

我个人认为媒体查询和容器查询就像鸡块和辣酱:它们都有各自的用途,但结合在一起,它们会震撼你的世界。我希望你玩得开心。

下一篇见。

来源:https ://blog.logrocket.com/choose-between-media-container-queries/

#media #css 

如何在媒体查询和容器查询之间进行选择

Como Escolher Entre Consultas De Mídia E Consultas De Contêiner

Todo mundo que acompanha os últimos eventos no mundo do design responsivo concordará que a introdução de consultas de contêiner CSS é um divisor de águas. É a coisa mais empolgante que aconteceu desde a introdução das consultas de mídia.

Mas o que é uma consulta de contêiner? Por que as consultas de contêiner são importantes e como você pode usá-las?

Neste artigo, responderemos a todas essas perguntas e muito mais nas seguintes seções:

  • O que é uma consulta de mídia em CSS?
  • O problema com consultas de mídia
  • Quando e como usar consultas de mídia
  • Quando e como usar consultas de contêiner

Sem perder mais tempo, vamos direto ao assunto.

O que é uma consulta de mídia em CSS?

Há muito tempo, a maioria dos sites tinha muitos problemas para renderizar componentes em diferentes tamanhos de tela, especialmente com a revolução dos telefones celulares. A maioria dos sites corrigiu esse problema criando um novo site com o domínio m.. Se você já usou m.facebook.com, é por isso.

Tudo isso foi antes das consultas de mídia. Com as consultas de mídia, os sites podem ser criados para caber em uma janela de visualização específica, então já se foram os dias de ampliar o zoom em seu smartphone para ver o que está no site.

As consultas de mídia fornecem uma declaração condicional em torno de alguns estilos, que são implementados ou não com base no fato de as condições serem atendidas ou não.

O problema com consultas de mídia

Embora as consultas de mídia tenham mudado muito, elas ainda têm um problema: elas não são reutilizáveis. Com consultas de mídia, você pode criar um elemento responsivo e implementá-lo e, embora pareça bom em um caso de uso padrão, provavelmente não funcionará tão bem se for movido para um contêiner diferente com propriedades CSS que afetam as dimensões do elemento. Para que funcione corretamente, você precisará adicionar muito mais propriedades CSS.

É aqui que entram as consultas de contêiner. Com as consultas de contêiner, agora você pode direcionar os próprios elementos individuais e permitir que eles se adaptem a praticamente qualquer contêiner ou layout.

As consultas de contêiner são como consultas de mídia; a única diferença é que eles tornam um contêiner ou elemento responsivo com base no espaço disponível para o contêiner, em vez da janela de visualização. Mas isso levanta a questão: ainda precisamos de consultas de mídia?

 

Quando e como usar consultas de mídia

A resposta para a pergunta acima é sim! Ainda há muitos casos de uso para consultas de mídia, apesar das consultas de contêiner resolverem suas limitações consideráveis.

As consultas de mídia podem e ainda devem ser usadas para layouts de página, que geralmente estão no nível superior do DOM e não aninhados em outro contêiner. Eles são mais adequados para isso porque o layout da página principal não deve se adaptar a nada além da janela de visualização.

As consultas de mídia também podem ser usadas para estilizar elementos globais como espaçamento, tamanho da fonte ou cores. Por exemplo, se você criar um site com tamanhos de fonte grandes, é provável que a fonte e o espaçamento sejam muito grandes para uma tela de celular. Isso pode ser corrigido com consultas de mídia como esta:

:root {
   --font-size-hl: 20px;
   --font-size-h2: 15px;
   --font-size-h3: 12px;
   --font-size-p: 8px;


   --letter-spacing: 8px;
}

@media (min-width: 300px) {
   :root {
       --font-size-hl: 13px;
       --font-size-h2: 10;
       --font-size-h3: 8px;
       --font-size-p: 5pxrem;

       --letter spacing: 4px;
   }
}

Um dos cenários de media queries em que brilha é quando você precisa remover um componente de uma página. Por exemplo, veja esta página inicial do Instagram:

Visualização da área de trabalho do feed do Instagram e barra de mensagens

Na área de trabalho, a barra de mensagens parece muito boa, mas a maioria dos dispositivos móveis não tem o tamanho da tela para exibi-la adequadamente. Com consultas de mídia, a guia de mensagem inteira pode ser removida e a mesma página será exibida assim.

A visualização móvel do Instagram oculta a barra de mensagens

Vale a pena notar que as consultas de mídia não servem apenas para detectar tamanhos de tela e como elas afetam os componentes.

As consultas de mídia também podem ser usadas para diferentes consultas relacionadas à preferência do usuário, como:

Quando e como usar consultas de contêiner

As consultas de contêiner permitem segmentar um contêiner específico e configurá-lo para exibição com base na largura e na altura do contêiner, sem precisar usar consultas de mídia. É usado principalmente para componentes de cartão, mas é flexível, então você pode usá-lo para vários componentes.

Com o CSS vanilla, as propriedades usadas nas consultas de contêiner compartilham muitas semelhanças com as propriedades que você está usando nas consultas de mídia. As únicas outras propriedades que você precisa aprender são:

  • container-type: Usado para declarar o elemento como um contêiner de consulta, permitindo que o componente filho consulte nele
  • container-name: Usado para atribuir um nome ao contêiner para filtragem adicional

Vamos dar uma olhada em um exemplo rápido de cartão. Primeiro, vamos elaborar um cartão com HTML.

<div class="container">
  <div class="contain-container contain-container--small">
    <h2>first example</h2>
    <div class="contain">
      <div class="contain__thumbnail"&gt;</div>
      <div class="contain__content">

        <h3 class="contain__title">Lorem Ipsium in english</h3>
        <p class="contain__description">But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. .</p>
      </div>
    </div>
  </div>
  <div class="contain-container contain-container--large">
    <h2>Second example</h2>
    <div class="contain">
      <div class="contain__thumbnail"></div>
      <div class="contain__content">
        <h3 class="contain__title">Lorem Ipsium in english</h3>
        <p class="contain__description">To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure.</p>
      </div>
    </div>
  </div>
</div>

O texto fictício é apenas uma versão traduzida do lorem ipsum. É minha peculiaridade pessoal.

Em seguida, vamos colocar o CSS.

body {
  background: #5f64e2;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica,
    Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  color: #fdf2f2;
}

.container {
  padding: 16px;
  margin: auto;
  display: flex;
  gap: 16px;
}

.contain-container {
  margin: 16px auto;
  flex-grow: 0;
  contain: layout inline-size;
  container-type: inline-size;
  --css-contain: layout inline-size;
}

.contain-container--small {
  width: 300px;
}

.contain-container--large {
  width: 600px;
}

.contain {
  padding: 16px;
  border-radius: 8px;
  background: black;
  margin-bottom: 16px;
  color: white;
}

  .contain__thumbnail {
    height: 130px;
    min-width: 130px;
    background: red;
    border-radius: 4px;
  }

  .contain__title {
    margin-top: 4px;
    margin-bottom: 8px;
  }

  .contain__description {
    margin: 0;
  }

O resultado do código acima ficará assim:

Dois cartões de consulta de contêiner

Ambos os cartões são basicamente os mesmos, exceto que um tem uma largura de 300px e o outro tem uma largura de 600px. Com consultas de contêiner, podemos fazer o cartão com a aparência correta e se comportar de maneira muito diferente com o código a seguir.

@container (min-width: 400px) {
  .contain {
    background-color: white;
    color: black;
    display: flex;
    gap: 16px;
  }
}

O que esse código faz é dizer a qualquer contêiner com mais de 400px de largura para ter uma cor de fundo branca, usar display: flexe ter uma cor de texto preta. O resultado ficará assim:

Cartões de consulta atualizados

As alterações no cartão à direita só se aplicam se o cartão tiver que ocupar um espaço com largura ≥ 400px, portanto, se não houver espaço suficiente para exibição ou se estiver sendo visualizado por um dispositivo móvel, os cartões serão revertidos para isso.

Cartões de consulta de contêiner na visualização para dispositivos móveis

Consultas de contêiner com CSS-in-JS

Eu sei que JSS, ou CSS-in-JS , é um tópico bastante controverso no momento. Há algumas pessoas, como esse cara que odeia JSS e não quer você perto dele, ou esse cara que adora e quer que você o use.

Quer você goste de JSS ou não, você tem que admitir que é muito útil. Assim como com CSS normal, é possível usar consultas de contêiner em JSS. Aqui está um exemplo muito simples de como funciona.

Primeiro, vamos construir quatro contêineres simples.

<div class=cquery>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? </h1>
</div>

<div class=cquery style=width:80%>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it?</h1>
</div>

<div class=cquery style=width:60%>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it?</h1>
</div>

<div class=cquery style=width:40%>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it?</h1>
</div>

Em seguida, vamos adicionar o JSS. Coloquei alguns comentários para facilitar a compreensão.

function JSinCSS() {
  //target an html element with id ='JSinCSS' and declare it tag
  let tag = document.querySelector("#JSinCSS");

  //if there is no html element with id ='#JSinCSS'
  if (!tag) {
    //create a style tag like this
    //<style></style>
    tag = document.createElement("style");

    //set id of style tag to be 'JSinCSS'
    //<style id='JSinCSS'></style>
    tag.id = "JSinCSS";
    //we call document.head.appendChild to append the style element to the head tag as a child.
    document.head.appendChild(tag);
  }

  //inside the style tag add innerHTML to it

  tag.innerHTML = `

    body:before {
      content: '${innerWidth} x ${innerHeight}';
    }

    .cquery {
      border: 4px solid red;
      background-color: green;
    }

    ${containerQuery('.cquery', 'this.offsetWidth > 500', `

      $this {
        background: blue;
      }

      $this h1 {
        font-size: 30pt;
      }

    `)}

    ${containerQuery('.cquery', 'this.offsetWidth > 800', `

      $this {
        background: purple;
      }

      $this h1 {
        font-size: 30pt;
      }

    `)}


    ${containerQuery('.cquery', 'this.offsetWidth > 1000', `

      $this {
        background: gold;
      }

      $this h1 {
        font-size: 30pt;
      }

    `)}

  `

}

function containerQuery(selector, test, stylesheet) {
    //target the container element and declare it tag
  var tag = document.querySelectorAll(selector);
  var style = "";
  var count = 1;

  for (var i = 0; i < tag.length; i++) {
      //tag.length return the number of nodes in tag
      // run a forLoop so when i == tag.length 
      //declare a function that returns test
    var func = new Function(`return ${test}`);
    var attr = (selector + test).replace(/[= "'><+\.]/g, "");

    if (func.call(tag[i])) {
      tag[i].setAttribute(`data-${attr}`, count);

      var css = stylesheet.replace(/\$this/g, `[data-${attr}="${count}"]`);

      style += css;

      count++;
    } else {
      tag[i].setAttribute(`data-${attr}`, "");
    }
  }

  return style;
}

//call the function in to listen to different events and call the function JSinCSS
window.addEventListener("load", JSinCSS);
window.addEventListener("resize", JSinCSS);
window.addEventListener("input", JSinCSS);
window.addEventListener("click", JSinCSS);

O código acima cria quatro contêineres diferentes e, em seguida, define uma consulta de contêiner com a containerQuerytag para que as cores dos contêineres mudem em tamanhos diferentes. O resultado fica assim.

Quatro cartões de consulta de contêiner em amarelo, roxo, azul e verde

No HTML, você pode ver que é o mesmo contêiner. Mas em uma largura de ≥1000px, a cor do contêiner se torna dourada. Em larguras de 800px e 500px, o contêiner fica roxo e azul, respectivamente. Abaixo disso, ele permanece em sua cor verde padrão. Portanto, se esses mesmos contêineres tiverem que ocupar um espaço ≤1000px, você obterá isso:

Os contêineres tornam-se roxos azuis e verdes em um espaço menor

Aqui está o link do CodePen se você quiser brincar um pouco com o código.

Conclusão

Todo o objetivo do design responsivo é alcançar versatilidade e eficiência e, com a introdução de consultas de contêiner, estamos um passo mais perto da perfeição no design responsivo. Ele resolve muitas das limitações das consultas de mídia, mas não substitui totalmente as consultas de mídia.

Pessoalmente, acho que consultas de mídia e consultas de contêiner são como nuggets de frango e molho picante: ambos têm seus usos separados, mas juntos, eles vão agitar seu mundo. Espero que você se divirta usando-os.

Nos vemos na próxima.

Fonte: https://blog.logrocket.com/choose-between-media-container-queries/

#media #css 

Como Escolher Entre Consultas De Mídia E Consultas De Contêiner

メディアクエリとコンテナクエリのどちらかを選択する

レスポンシブデザインの世界の最新のイベントに遅れずについていく人は誰でも、CSSコンテナクエリの導入がゲームチェンジャーであることに同意するでしょう。これは、メディアクエリの導入以来起こった最もエキサイティングなことです。

しかし、コンテナクエリとは何ですか?コンテナクエリが重要なのはなぜですか。また、それらをどのように使用できますか?

この記事では、次のセクションを通じて、これらすべての質問とその他の質問に回答します。

  • CSSのメディアクエリとは何ですか?
  • メディアクエリの問題
  • メディアクエリをいつどのように使用するか
  • コンテナクエリをいつどのように使用するか

もう時間を無駄にすることなく、すぐに始めましょう。

CSSのメディアクエリとは何ですか?

ずっと前に、ほとんどのWebサイトは、特に携帯電話の革命で、さまざまな画面サイズでコンポーネントをレンダリングするのに多くの問題を抱えていました。ほとんどのWebサイトは、ドメインを使用して新しいWebサイトを作成することにより、この問題を修正しましたm.。これまでに使用したことがある場合m.facebook.comは、これが理由です。

メディアクエリの前にあったすべて。メディアクエリを使用すると、特定のビューポートに合わせてWebサイトを構築できるため、スマートフォンを拡大してWebサイトの内容を確認する時代は終わりました。

メディアクエリは、いくつかのスタイルに関する条件付きステートメントを提供します。これらのスタイルは、条件が満たされているかどうかに基づいて実装されるかどうかに基づいて実装されます。

メディアクエリの問題

メディアクエリは大きく変化しましたが、それでも1つの問題がありました。それは、再利用できないということです。メディアクエリを使用すると、レスポンシブ要素を作成して実装できます。標準のユースケースでは見栄えがよくなりますが、要素のサイズに影響するCSSプロパティを持つ別のコンテナに移動すると、おそらくうまく機能しません。正しく機能させるには、CSSプロパティをさらに追加する必要があります。

ここでコンテナクエリが登場します。コンテナクエリを使用すると、個々の要素自体をターゲットにして、事実上すべての特定のコンテナまたはレイアウトに適応できるようになります。

コンテナクエリはメディアクエリのようなものです。唯一の違いは、ビューポートではなく、コンテナで使用可能なスペースに基づいてコンテナまたは要素をレスポンシブにすることです。しかし、それは疑問を投げかけます:私たちはもうメディアクエリさえ必要ですか?

 

メディアクエリをいつどのように使用するか

上記の質問に対する答えはイエスです!コンテナクエリがかなりの制限を解決しているにもかかわらず、メディアクエリのユースケースはまだたくさんあります。

メディアクエリは、通常DOMの最上位にあり、別のコンテナにネストされていないページレイアウトに使用できます。メインページのレイアウトはビューポート以外のものに適応してはならないため、これらはこれに最も適しています。

メディアクエリを使用して、間隔、フォントサイズ、色などのグローバル要素のスタイルを設定することもできます。たとえば、フォントサイズが大きいウェブサイトを構築する場合、モバイル画面にはフォントと間隔が大きすぎる可能性があります。これは、次のようなメディアクエリで修正できます。

:root {
   --font-size-hl: 20px;
   --font-size-h2: 15px;
   --font-size-h3: 12px;
   --font-size-p: 8px;


   --letter-spacing: 8px;
}

@media (min-width: 300px) {
   :root {
       --font-size-hl: 13px;
       --font-size-h2: 10;
       --font-size-h3: 8px;
       --font-size-p: 5pxrem;

       --letter spacing: 4px;
   }
}

輝かしいメディアクエリのシナリオの1つは、ページからコンポーネントを削除する必要がある場合です。たとえば、次のInstagramホームページを見てください。

デスクトップでは、メッセージバーは非常に見栄えがしますが、ほとんどのモバイルデバイスには、これを適切に表示するための画面サイズがありません。メディアクエリを使用すると、メッセージタブ全体を削除でき、同じページが次のように表示されます。

メディアクエリは、画面サイズとそれらがコンポーネントにどのように影響するかを検出するためだけのものではないことに注意してください。

メディアクエリは、次のようなユーザー設定に関連するさまざまなクエリにも使用できます。

コンテナクエリをいつどのように使用するか

コンテナクエリを使用すると、メディアクエリを使用せずに、特定のコンテナをターゲットにして、コンテナの幅と高さに基づいて表示するように設定できます。主にカードコンポーネントに使用されますが、柔軟性があるため、複数のコンポーネントに使用できます。

バニラCSSでは、コンテナクエリで使用されるプロパティは、メディアクエリで使用しているプロパティと多くの類似点を共有しています。学習する必要がある他のプロパティは次のとおりです。

  • container-type:要素をクエリコンテナとして宣言し、子コンポーネントが要素に対してクエリを実行できるようにするために使用されます
  • container-name:さらにフィルタリングするためにコンテナに名前を割り当てるために使用されます

カードの簡単な例を見てみましょう。まず、HTMLでカードを作成しましょう。

<div class="container">
  <div class="contain-container contain-container--small">
    <h2>first example</h2>
    <div class="contain">
      <div class="contain__thumbnail"&gt;</div>
      <div class="contain__content">

        <h3 class="contain__title">Lorem Ipsium in english</h3>
        <p class="contain__description">But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. .</p>
      </div>
    </div>
  </div>
  <div class="contain-container contain-container--large">
    <h2>Second example</h2>
    <div class="contain">
      <div class="contain__thumbnail"></div>
      <div class="contain__content">
        <h3 class="contain__title">Lorem Ipsium in english</h3>
        <p class="contain__description">To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure.</p>
      </div>
    </div>
  </div>
</div>

ダミーテキストは、loremipsumの翻訳版にすぎません。それは私の個人的な癖です。

次に、CSSを入れましょう。

body {
  background: #5f64e2;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica,
    Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  color: #fdf2f2;
}

.container {
  padding: 16px;
  margin: auto;
  display: flex;
  gap: 16px;
}

.contain-container {
  margin: 16px auto;
  flex-grow: 0;
  contain: layout inline-size;
  container-type: inline-size;
  --css-contain: layout inline-size;
}

.contain-container--small {
  width: 300px;
}

.contain-container--large {
  width: 600px;
}

.contain {
  padding: 16px;
  border-radius: 8px;
  background: black;
  margin-bottom: 16px;
  color: white;
}

  .contain__thumbnail {
    height: 130px;
    min-width: 130px;
    background: red;
    border-radius: 4px;
  }

  .contain__title {
    margin-top: 4px;
    margin-bottom: 8px;
  }

  .contain__description {
    margin: 0;
  }

上記のコードの結果は次のようになります。

どちらのカードもほぼ同じですが、一方の幅が300ピクセルで、もう一方のカードの幅が600ピクセルである点が異なります。コンテナクエリを使用すると、次のコードを使用して、カードの外観と動作を大きく変えることができます。

@container (min-width: 400px) {
  .contain {
    background-color: white;
    color: black;
    display: flex;
    gap: 16px;
  }
}

そのコードが行うことは、幅が400pxを超えるコンテナに、背景色を白にし、を使用しdisplay: flex、テキストの色を黒にするように指示することです。結果は次のようになります。

右側のカードへの変更は、カードが400px以上の幅のスペースを占める必要がある場合にのみ適用されるため、表示するのに十分なスペースがない場合、またはモバイルデバイスで表示されている場合、カードは元に戻ります。これに。

CSS-in-JSを使用したコンテナクエリ

JSS、またはCSS-in-JSは、現在かなり物議を醸しているトピックであることを私は知っています。JSSが嫌いで、近くにいることを望まないこの人や、 JSSを絶対に愛していて、使ってほしいという人がいます。

JSSが好きかどうかにかかわらず、それがかなり便利であることを認めなければなりません。通常のCSSと同様に、JSSでコンテナクエリを使用することができます。これがどのように機能するかの非常に簡単な例です。

まず、4つの簡単なコンテナを作成しましょう。

<div class=cquery>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? </h1>
</div>

<div class=cquery style=width:80%>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it?</h1>
</div>

<div class=cquery style=width:60%>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it?</h1>
</div>

<div class=cquery style=width:40%>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it?</h1>
</div>

次に、JSSを追加しましょう。わかりやすくするためにコメントを入れました。

function JSinCSS() {
  //target an html element with id ='JSinCSS' and declare it tag
  let tag = document.querySelector("#JSinCSS");

  //if there is no html element with id ='#JSinCSS'
  if (!tag) {
    //create a style tag like this
    //<style></style>
    tag = document.createElement("style");

    //set id of style tag to be 'JSinCSS'
    //<style id='JSinCSS'></style>
    tag.id = "JSinCSS";
    //we call document.head.appendChild to append the style element to the head tag as a child.
    document.head.appendChild(tag);
  }

  //inside the style tag add innerHTML to it

  tag.innerHTML = `

    body:before {
      content: '${innerWidth} x ${innerHeight}';
    }

    .cquery {
      border: 4px solid red;
      background-color: green;
    }

    ${containerQuery('.cquery', 'this.offsetWidth > 500', `

      $this {
        background: blue;
      }

      $this h1 {
        font-size: 30pt;
      }

    `)}

    ${containerQuery('.cquery', 'this.offsetWidth > 800', `

      $this {
        background: purple;
      }

      $this h1 {
        font-size: 30pt;
      }

    `)}


    ${containerQuery('.cquery', 'this.offsetWidth > 1000', `

      $this {
        background: gold;
      }

      $this h1 {
        font-size: 30pt;
      }

    `)}

  `

}

function containerQuery(selector, test, stylesheet) {
    //target the container element and declare it tag
  var tag = document.querySelectorAll(selector);
  var style = "";
  var count = 1;

  for (var i = 0; i < tag.length; i++) {
      //tag.length return the number of nodes in tag
      // run a forLoop so when i == tag.length 
      //declare a function that returns test
    var func = new Function(`return ${test}`);
    var attr = (selector + test).replace(/[= "'><+\.]/g, "");

    if (func.call(tag[i])) {
      tag[i].setAttribute(`data-${attr}`, count);

      var css = stylesheet.replace(/\$this/g, `[data-${attr}="${count}"]`);

      style += css;

      count++;
    } else {
      tag[i].setAttribute(`data-${attr}`, "");
    }
  }

  return style;
}

//call the function in to listen to different events and call the function JSinCSS
window.addEventListener("load", JSinCSS);
window.addEventListener("resize", JSinCSS);
window.addEventListener("input", JSinCSS);
window.addEventListener("click", JSinCSS);

上記のコードは、4つの異なるコンテナーを作成し、コンテナーcontainerQueryの色が異なるサイズで変化するように、タグを使用してコンテナークエリを設定します。結果は次のようになります。

HTMLから、同じコンテナであることがわかります。ただし、幅が1000px以上の場合、コンテナの色は金色になります。800pxと500pxの幅では、コンテナはそれぞれ紫と青になります。その下では、デフォルトの緑色のままです。したがって、これらの同じコンテナが1000px以下のスペースを占有する必要がある場合は、次のようになります。

コードを少し試してみたい場合は、CodePenのリンクを次に示します。

結論

レスポンシブデザインの全体的なポイントは、汎用性と効率性を実現することです。コンテナクエリの導入により、レスポンシブデザインの完成度に一歩近づきました。メディアクエリの多くの制限を解決しますが、メディアクエリを完全に置き換えるわけではありません。

私は個人的に、メディアクエリとコンテナクエリはチキンナゲットとホットソースのようなものだと思います。どちらも別々に使用されますが、一緒にすると、あなたの世界を揺るがします。楽しんで使っていただければ幸いです。

次でお会いしましょう。

ソース:https ://blog.logrocket.com/choose-between-media-container-queries/

#media #css 

メディアクエリとコンテナクエリのどちらかを選択する

How to Choose between Media Queries and Container Queries

Everyone who keeps up with the latest events in the world of responsive design will agree that the introduction of CSS container queries is a game changer. It’s the most exciting thing that has happened since the introduction of, well, media queries.

But what is a container query? Why are container queries important and how can you use them?

In this article, we’re going to answer all of those questions and more through the following sections:

  • What is a media query in CSS?
  • The problem with media queries
  • When and how to use media queries
  • When and how to use container queries

Without wasting any more time, let’s get right into it.

What is a media query in CSS?

Long ago, most websites had a lot of trouble rendering components on different screen sizes, especially with the mobile phone revolution. Most websites fixed that problem by creating a new website with the domain m.. If you’ve ever used m.facebook.com, this is why.

All that was before media queries. With media queries, websites can be built to fit a particular viewport, so gone are the days of zooming in on your smartphone to see what’s on the website.

Media queries provide a conditional statement around some styles, which are then implemented or not based on whether the conditions are met or not.

The problem with media queries

While media queries changed a lot, they still had one problem: they’re not reusable. With media queries, you can create a responsive element and implement it, and even though it looks good in a standard use case, it probably won’t work as well if it’s moved to a different container with CSS properties that affect element dimensions. For it to work properly, you’ll need to add many more CSS properties.

Here’s where container queries come in. With container queries, you can now target individual elements themselves and enable them to adapt to virtually any given container or layout.

Container queries are like media queries; the only difference is they make a container or an element responsive based on the space available to the container, rather than the viewport. But that raises the question: Do we even need media queries anymore?

 

When and how to use media queries

The answer to the above question is yes! There are still a ton of use cases for media queries, despite container queries solving their considerable limitations.

Media queries can and should still be used for page layouts, which are usually at the very top level of the DOM and not nested in another container. They’re best suited for this because the main page layout should not adapt to anything other than the viewport.

Media queries can also be used to style global elements like spacing, font size, or colors. For example, if you build a website with large font sizes, chances are the font and spacing will be too large for a mobile screen. That can be fixed with media queries like this:

:root {
   --font-size-hl: 20px;
   --font-size-h2: 15px;
   --font-size-h3: 12px;
   --font-size-p: 8px;


   --letter-spacing: 8px;
}

@media (min-width: 300px) {
   :root {
       --font-size-hl: 13px;
       --font-size-h2: 10;
       --font-size-h3: 8px;
       --font-size-p: 5pxrem;

       --letter spacing: 4px;
   }
}

One of the scenarios media queries in which shine is when you have to remove a component from a page. For instance, look at this Instagram home page:

Desktop view of Instagram feed and message bar

On desktop, the message bar looks really good, but most mobile devices do not have the screen size to display this appropriately. With media queries, the entire message tab can be removed and the same page will display like this.

Instagram mobile view hides message bar

It’s worth noting that media queries aren’t just for detecting screen sizes and how they affect components.

Media queries can also be used for different queries related to user preference, such as:

When and how to use container queries

Container queries allow you to target a specific container and configure it to display based on the width and height of the container, without having to use media queries. It’s mostly used for card components, but it’s flexible, so you can use it for multiple components.

With vanilla CSS, the properties used in container queries share a lot of similarities with the properties you’ve been using in media queries. The only other properties you need to learn are:

  • container-type: Used to declare the element as a query container, allowing the child component to query against it
  • container-name: Used to assign a name to the container for further filtering

Let’s take a look at a quick card example. First, let’s draft out a card with HTML.

<div class="container">
  <div class="contain-container contain-container--small">
    <h2>first example</h2>
    <div class="contain">
      <div class="contain__thumbnail"&gt;</div>
      <div class="contain__content">

        <h3 class="contain__title">Lorem Ipsium in english</h3>
        <p class="contain__description">But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. .</p>
      </div>
    </div>
  </div>
  <div class="contain-container contain-container--large">
    <h2>Second example</h2>
    <div class="contain">
      <div class="contain__thumbnail"></div>
      <div class="contain__content">
        <h3 class="contain__title">Lorem Ipsium in english</h3>
        <p class="contain__description">To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure.</p>
      </div>
    </div>
  </div>
</div>

The dummy text is just a translated version of lorem ipsum. It’s my personal quirk.

Next, let’s put in the CSS.

body {
  background: #5f64e2;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica,
    Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  color: #fdf2f2;
}

.container {
  padding: 16px;
  margin: auto;
  display: flex;
  gap: 16px;
}

.contain-container {
  margin: 16px auto;
  flex-grow: 0;
  contain: layout inline-size;
  container-type: inline-size;
  --css-contain: layout inline-size;
}

.contain-container--small {
  width: 300px;
}

.contain-container--large {
  width: 600px;
}

.contain {
  padding: 16px;
  border-radius: 8px;
  background: black;
  margin-bottom: 16px;
  color: white;
}

  .contain__thumbnail {
    height: 130px;
    min-width: 130px;
    background: red;
    border-radius: 4px;
  }

  .contain__title {
    margin-top: 4px;
    margin-bottom: 8px;
  }

  .contain__description {
    margin: 0;
  }

The result of the above code will look like this:

Two container query cards

Both cards are largely the same, except that one has a width of 300px and the other has a width of 600px. With container queries, we can make the card on the right look and behave very differently with the following code.

@container (min-width: 400px) {
  .contain {
    background-color: white;
    color: black;
    display: flex;
    gap: 16px;
  }
}

What that code does is tell any container that is over 400px wide to have a background color of white, use display: flex, and have a text color of black. The result will look like this:

Updated query cards

The changes to the card on the right only apply if the card has to occupy a space with a width of ≥ 400px, so if there’s not enough space for it to display, or if it’s being viewed by a mobile device, the cards will revert to this.

Container Query cards in mobile view

Container queries with CSS-in-JS

I know JSS, or CSS-in-JS, is a pretty controversial topic right now. There are a couple of people, like this guy who hates JSS and doesn’t want you anywhere near it, or this guy who absolutely loves it and wants you to use it.

Whether you like JSS or not, you’ve got to admit it’s pretty handy. Just like with normal CSS, it’s possible to use container queries in JSS. Here’s a very simple example of how it works.

First, let’s build four simple containers.

<div class=cquery>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? </h1>
</div>

<div class=cquery style=width:80%>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it?</h1>
</div>

<div class=cquery style=width:60%>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it?</h1>
</div>

<div class=cquery style=width:40%>
  <h1>To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it?</h1>
</div>

Next, let’s add the JSS. I’ve put some comments in to make it easily understandable.

function JSinCSS() {
  //target an html element with id ='JSinCSS' and declare it tag
  let tag = document.querySelector("#JSinCSS");

  //if there is no html element with id ='#JSinCSS'
  if (!tag) {
    //create a style tag like this
    //<style></style>
    tag = document.createElement("style");

    //set id of style tag to be 'JSinCSS'
    //<style id='JSinCSS'></style>
    tag.id = "JSinCSS";
    //we call document.head.appendChild to append the style element to the head tag as a child.
    document.head.appendChild(tag);
  }

  //inside the style tag add innerHTML to it

  tag.innerHTML = `

    body:before {
      content: '${innerWidth} x ${innerHeight}';
    }

    .cquery {
      border: 4px solid red;
      background-color: green;
    }

    ${containerQuery('.cquery', 'this.offsetWidth > 500', `

      $this {
        background: blue;
      }

      $this h1 {
        font-size: 30pt;
      }

    `)}

    ${containerQuery('.cquery', 'this.offsetWidth > 800', `

      $this {
        background: purple;
      }

      $this h1 {
        font-size: 30pt;
      }

    `)}


    ${containerQuery('.cquery', 'this.offsetWidth > 1000', `

      $this {
        background: gold;
      }

      $this h1 {
        font-size: 30pt;
      }

    `)}

  `

}

function containerQuery(selector, test, stylesheet) {
    //target the container element and declare it tag
  var tag = document.querySelectorAll(selector);
  var style = "";
  var count = 1;

  for (var i = 0; i < tag.length; i++) {
      //tag.length return the number of nodes in tag
      // run a forLoop so when i == tag.length 
      //declare a function that returns test
    var func = new Function(`return ${test}`);
    var attr = (selector + test).replace(/[= "'><+\.]/g, "");

    if (func.call(tag[i])) {
      tag[i].setAttribute(`data-${attr}`, count);

      var css = stylesheet.replace(/\$this/g, `[data-${attr}="${count}"]`);

      style += css;

      count++;
    } else {
      tag[i].setAttribute(`data-${attr}`, "");
    }
  }

  return style;
}

//call the function in to listen to different events and call the function JSinCSS
window.addEventListener("load", JSinCSS);
window.addEventListener("resize", JSinCSS);
window.addEventListener("input", JSinCSS);
window.addEventListener("click", JSinCSS);

The code above creates four different containers and then sets a container query with the containerQuery tag so that the colors of the containers change at different sizes. The result looks like this.

Four container query cards in yellow, purple, blue, and green

From the HTML, you can see it’s the same container. But at a width of ≥1000px, the container color becomes gold. At widths of 800px and 500px, the container becomes purple and blue, respectively. Below that, it stays in its default green color. So, if these same containers have to occupy a space that’s ≤1000px, you’ll get this:

Containers become purple blue and green in smaller space

Here’s the CodePen link if you want to play around with the code a bit.

Conclusion

The entire point of responsive design is achieving versatility and efficiency, and with the introduction of container queries, we’re one step closer to perfection in responsive design. It solves a lot of the limitations of media queries, but it doesn’t entirely replace media queries.

I personally think media queries and container queries are like chicken nuggets and hot sauce: they both have their uses separately, but together, they’ll rock your world. I hope you have fun using them.

See you in the next one.

Source: https://blog.logrocket.com/choose-between-media-container-queries/

#media #css 

 How to Choose between Media Queries and Container Queries
Alex Rock

Alex Rock

1654496231

Understanding the Crypto Fundraising Models

What is an Initial Coin Offering (ICO)?

In the crypto world, an Initial Coin Offering (ICO) is equivalent to an Initial Public Offering (IPO) (IPO). The term "Initial Coin Offering" refers to a fundraising model that aids in the capitalization of the cryptocurrency industry. An ICO can be launched by a company or a new coin to raise funds. Interested investors can participate in the initial coin offering in exchange for a new crypto token issued by the company.

The process begins with a new or established company looking to raise capital for growth. It is a fundraising event for a new cryptocurrency asset, company, or venture.

What is an Initial DEX Offering (IDO)?

A crypto token offering that runs on a Decentralized Exchange is an Initial Decentralized Exchange (DEX) Offering. Liquidity pools (LP) play an essential role by providing liquidity after the sale. The initial DEX offering during a token generation event allows users to lock their funds in exchange for new tokens, providing a cost-effective and more accessible way for projects to distribute tokens.

Initial DEX offerings are similar to ICOs and IEOs in that they seek to raise funds and bootstrap a project. Unlike ICOs and IEOs, where tokens are sold before listing, IDOs are immediately listed on a decentralized exchange.

What is an Initial Exchange Offering (IEO)?

An Initial Exchange Offering (IEO) is a type of crowdfunding managed by an exchange platform. Unlike an ICO, where the project team is in charge of fundraising, an Initial Exchange Offering is made through an exchange platform. Users can directly purchase tokens in IEO using funds from their exchange wallet.

IEO is a simple fundraising model in which users only need an exchange platform account with some funds to participate. Where the exchange is staking its reputation for a project on its platform, IEOs provide a high level of trust and transparency.

What is an Initial Farming Offering (IFO)?

Initial Farming Offering (IFO) is a fundraising model that assists newly launched Defi projects in raising capital through participation in pre-sales events. The Initial Funding Offering (IFO) is the successor to the Initial Coin Offering (ICO), which depicts a crowdsourcing method used by crypto projects to raise capital in the early stages.

Investors can raise the capital needed for the available projects by participating in DEX's re-sales event. IFOs, which serve to raise funds for crypto projects, are both similar and distinct from IEOs and ICOs.

What is an Initial Liquidity Offering (ILO)?

An Initial Liquidity Offering (ILO) is a fundraising model in which a new token is offered to buyers who agree to contribute to a liquidity pool. Because the token is attracting new buyers, the Automated Market Maker (AMM) can function. It allows multiple projects and startups to raise funds by selling tokens on Defi-based DEX platforms instead of conducting an ICO.

ILOs are simple to carry out on Defi-based DEX platforms because they have many investors who may be interested in purchasing the crypto tokens immediately for a higher price. These DEXs use the AMM mechanism, which manages liquidity pools through highly skilled liquidity providers.

What is an Initial NFT Offering (INO)?

NFTs have played various roles in reaching out to the target audience and generating interest in new tokens or any business. NFT can be used as a marketing tool to attract customers by providing them with some benefit that benefits the NFT holder. At such times, the initial offering of NFT is the opportunity for the customer to acquire the NFT and use the utility for a specific project.

This INO (Initial NFT Offering) can be used as a marketing strategy or fundraising model. The main thing is to look at the number of people interested in the use case and the project's popularity. Sometimes a free NFT offering will include a few tasks to complete that will help spread the project to more people.

Please contact Suffescom Solutions, an IDO Development Company, if you want to develop any fundraising models.

#news  #suffescom  #hit  #hindustantimes  #idodevelopmentcompany  #media  #blockchain  #developer  #crypto  #dapp  #defi  #metaverse  #web3  #web3  #cryptowallet  #crypto  #wallet  
 

Michael Elliot

Michael Elliot

1654240328

Top 5 DEX Development Companies

Since the idea of Initial Dex Offerings (IDO) came up in the late 2010s, these have been a part of many crypto projects that are slowly becoming successful. Launchpads have helped bring new businesses into the crypto space by putting them in front of a larger group of investors. Also, the current crypto climate looks like it will bring a lot more wealth in the future as new uses are found. So, a business based on an IDO launchpad could be the best way for an entrepreneur to get started if they want to take advantage of the crypto world's potential by helping new projects. Even though a lot of companies say they are experts at making IDO launchpads, only a few of them really are, which can be seen by the wide range of clients they have worked with. In this blog, we'll look at the top five companies that build IDO launchpads.

1. Suffescom Solution: Suffescom Solutions has been since 2011 before the first popular non-fungible tokens (NFTs) went public. And The firm has started pioneering the development of various blockchain-based applications with a global presence with dedicated developers on various technologies. Also many time awarded by the national media groups such as Hindustan Times in India. The Suffescom Solutions Pvt. Ltd. was awarded by Shri Som Parkash (Honorable Union Minister of State for Commerce & Industry) at “Business & Entrepreneurs - Felicitation Ceremony 2022“ organized by leading print media Hindustan Times. According to some reports, the company’s on-demand IDO crypto Launchpad Development services have been one of their warm products. The experienced blockchain developers in the firm have the capability to develop IDO launchpad platforms from scratch and ready-made white label cryptocurrency exchange development solutions. Since the firm has a customer-centric stand, your requirements will be fulfilled without fail, and its services come at affordable prices. The firm also offers excellent services related to the development of crypto exchanges, NFT applications, DeFi applications, and more.

  • Hourly Rate: $25 — $49 / hr
  • Employees: 249–499
  • Year of Foundation: 2011
  • Location: United States of America, India, Australia, Dubai

2. Best Web3 Development: Best Web3 Development Firm is a top-notch web3 platform development firm in USA with advanced and latest technology. It has highly experienced 200+ blockchain developers understand your dream and turn it into reality. It is working in the technology since 2010 when blockchain and crypto booming at wide range and It came with a unique ideas regarding new internet era. Best Web3.0 Development company is ready to shape a revolutionary platform. It has plethora of solutions regarding web3.0 developers and consulting team to launch AR, VR and extended reality platform. Following are the services:

Whitepaper Drafting

Website Design

Token Creation

Marketing

Bounty Management

Listing services

Coin Boosting

Product Development

3. RisingMax Consultant

RisingMax is the next name in the top companies for cryptocurrency wallet development solutions. The organization is led by top leaders and managers who never compromise with the quality of the services. The company earned its reputation and clients’ trust by delivering cutting-edge blockchain solutions. The team members have hands on the latest technologies like cloud, chatbot, IoT, AI, machine learning, etc.

RisingMax has served clients from more than 15+ countries with an innovative and agile approach. This company’s methodology has helped many businesses to grow exponentially in no time. The blockchain developers from RisingMax strive to unlock the opportunity for their clients in the blockchain journey. RisingMax is the one-stop destination for businesses looking for crypto development services.

  • Hourly Rate: $25 — $49 / hr
  • Employees: 180
  • Year of Foundation: 2011
  • Location: NYC, Bangalore, Sydney

4. Blockchain Web Devs

Antiersolutions stands on the top of the list of crypto development companies due to its high-tech development solutions. The company is known for its excellence in delivering feasible, cost-effective, and on-time services. By adopting the latest technologies and frameworks, the antiersolution provides a high user experience that helps the businesses retain the customers and generate huge revenue.

Through the agile approach, the company comes up with creative solutions for the emerging problems related to blockchain business issues. Antiersolutions has rich expertise in blockchain development, on-demand app solutions, Machine learning, AI, cryptocurrency, etc. With the experience gained over the years, the company can tackle complex challenges while caring for clients’ requirements.

  • Hourly Rate: $25 / hr
  • Employees: 49–199
  • Year of Foundation: 2015
  • Location: NYC, Dubai, Singapore

5. Idealogic

Idealogic refers to a full-cycle software advancement company located at Kyiv, Ukraine, with significant QA assurance, custom software development, product design expertise, and post-release support under Logistics, Fintech, Retail, plus Business Intelligence domains. They focus on business with entrepreneurs and startup founders keen on improving their ideas transparently and flexibly with a cost-effective budget.

They do worry about every project and consider all as their own. Initially, you might think of it as marketing material; however, you will understand its approach right after sending your message. They take minutes to respond to an answer rather than hours, plus you will continually believe that they are there for you.

  • Hourly Rate: $25 — $49/hr
  • Employees: 10–49
  • Year of Foundation: 2016
  • Location: Ukraine, United States

#news #suffescom #HIT #hindustantimes #media #blockchain #developer #crypto #app 

Top 5 DEX Development Companies

React Native Module for Playing Sound Clips

react-native-sound

React Native module for playing sound clips on iOS, Android, and Windows.

Be warned, this software is alpha quality and may have bugs. Test on your own and use at your own risk!

Feature matrix

React-native-sound does not support streaming. See #353 for more info. Of course, we would welcome a PR if someone wants to take this on.

In iOS, the library uses AVAudioPlayer, not AVPlayer.

FeatureiOSAndroidWindows
Load sound from the app bundle
Load sound from other directories
Load sound from the network 
Play sound
Playback completion callback
Pause
Resume
Stop
Reset  
Release resource
Get duration
Get number of channels  
Get/set volume
Get system volume 
Set system volume  
Get/set pan  
Get/set loops
Get/set exact loop count  
Get/set current time
Set speed 

Installation

First install the npm package from your app directory:

npm install react-native-sound --save

Then link it automatically using:

react-native link react-native-sound

If you encounter this error

undefined is not an object (evaluating 'RNSound.IsAndroid')

you may additionally need to fully clear your build caches for Android. You can do this using

cd android
./gradlew cleanBuildCache

After clearing your build cache, you should execute a new react-native build.

If you still experience issues, know that this is the most common build issue. See #592 and the several issues linked from it for possible resolution. A pull request with improved documentation on this would be welcome!

Manual Installation Notes

Please see the Wiki for these details https://github.com/zmxv/react-native-sound/wiki/Installation

Help with React-Native-Sound

  • For react-native-sound developers
  • For help using react-native-sound

Demo project

https://github.com/zmxv/react-native-sound-demo

Player

https://github.com/benevbright/react-native-sound-playerview

Basic usage

First you'll need to add audio files to your project.

  • Android: Save your sound clip files under the directory android/app/src/main/res/raw. Note that files in this directory must be lowercase and underscored (e.g. my_file_name.mp3) and that subdirectories are not supported by Android.
  • iOS: Open Xcode and add your sound files to the project (Right-click the project and select Add Files to [PROJECTNAME])
// Import the react-native-sound module
var Sound = require('react-native-sound');

// Enable playback in silence mode
Sound.setCategory('Playback');

// Load the sound file 'whoosh.mp3' from the app bundle
// See notes below about preloading sounds within initialization code below.
var whoosh = new Sound('whoosh.mp3', Sound.MAIN_BUNDLE, (error) => {
  if (error) {
    console.log('failed to load the sound', error);
    return;
  }
  // loaded successfully
  console.log('duration in seconds: ' + whoosh.getDuration() + 'number of channels: ' + whoosh.getNumberOfChannels());

  // Play the sound with an onEnd callback
  whoosh.play((success) => {
    if (success) {
      console.log('successfully finished playing');
    } else {
      console.log('playback failed due to audio decoding errors');
    }
  });
});

// Reduce the volume by half
whoosh.setVolume(0.5);

// Position the sound to the full right in a stereo field
whoosh.setPan(1);

// Loop indefinitely until stop() is called
whoosh.setNumberOfLoops(-1);

// Get properties of the player instance
console.log('volume: ' + whoosh.getVolume());
console.log('pan: ' + whoosh.getPan());
console.log('loops: ' + whoosh.getNumberOfLoops());

// Seek to a specific point in seconds
whoosh.setCurrentTime(2.5);

// Get the current playback point in seconds
whoosh.getCurrentTime((seconds) => console.log('at ' + seconds));

// Pause the sound
whoosh.pause();

// Stop the sound and rewind to the beginning
whoosh.stop(() => {
  // Note: If you want to play a sound after stopping and rewinding it,
  // it is important to call play() in a callback.
  whoosh.play();
});

// Release the audio player resource
whoosh.release();

Notes

  • To minimize playback delay, you may want to preload a sound file without calling play() (e.g. var s = new Sound(...);) during app initialization. This also helps avoid a race condition where play() may be called before loading of the sound is complete, which results in no sound but no error because loading is still being processed.
  • You can play multiple sound files at the same time. Under the hood, this module uses AVAudioSessionCategoryAmbient to mix sounds on iOS.
  • You may reuse a Sound instance for multiple playbacks.
  • On iOS, the module wraps AVAudioPlayer that supports aac, aiff, mp3, wav etc. The full list of supported formats can be found at https://developer.apple.com/library/content/documentation/MusicAudio/Conceptual/CoreAudioOverview/SupportedAudioFormatsMacOSX/SupportedAudioFormatsMacOSX.html
  • On Android, the module wraps android.media.MediaPlayer. The full list of supported formats can be found at https://developer.android.com/guide/topics/media/media-formats.html
  • On Android, the absolute path can start with '/sdcard/'. So, if you want to access a sound called "my_sound.mp3" on Downloads folder, the absolute path will be: '/sdcard/Downloads/my_sound.mp3'.
  • You may chain non-getter calls, for example, sound.setVolume(.5).setPan(.5).play().

Audio on React Native

Contributing

Pull requests welcome with bug fixes, documentation improvements, and enhancements.

When making big changes, please open an issue first to discuss.

Download Details:
Author: zmxv
Source Code: https://github.com/zmxv/react-native-sound
License: MIT license

#react  #reactnative  #mobileapp  #javascript #java 

React Native Module for Playing Sound Clips
Jake  Murphy

Jake Murphy

1635181200

How to Create Social Media Button Hover Effect

Hello, world!!! In this video, we created an awesome hover effect animation on social media icons from font-awesome. We play around with the advanced box-shadow that takes in two layers to achieve the effect. We also created a bunch of animations on the pseudo element and the icon. You may say it to be a continuation of a video that I created a couple of months ago that also had almost the same functionality. The only new thing, added in this project was the last animation on the icon container that is mind-blowing 🤯.

#media 

How to Create Social Media Button Hover Effect

Determine Multimedia File Properties Like Width, Height, Duration

media_info .Utilizes platform code to determine audio, video & photo properties.

Depending on the underlying platform version, various workarounds will be applied to fetch the fields.

Currently supported properties:

  • width
  • height
  • frame rate
  • duration (in milliseconds)
  • mime type
  • number of tracks

Additionally, thumbnails can be generated.

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add media_info

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):


dependencies:
  media_info: ^0.8.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:media_info/media_info.dart'; 

example/lib/main.dart

import 'dart:async';
import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:media_info/media_info.dart';
import 'package:path_provider/path_provider.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class Resolution {
  const Resolution(this.w, this.h);

  final int w;
  final int h;
}

const List<Resolution> _resolutions = [
  Resolution(384, 216),
  Resolution(512, 288),
  Resolution(640, 360),
  Resolution(768, 432),
  Resolution(896, 504),
  Resolution(1024, 576),
  Resolution(1152, 648),
  Resolution(1280, 720),
  Resolution(1408, 792),
  Resolution(1536, 864),
  Resolution(1664, 936),
  Resolution(1792, 1008),
  Resolution(1920, 1080),
];

class _MyAppState extends State<MyApp> {
  String? _file;
  Map<String, dynamic>? _mediaInfoCache;
  final Map<String, Future<String>> _thumbnails = <String, Future<String>>{};

  final MediaInfo _mediaInfo = MediaInfo();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      showPerformanceOverlay: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Media Info App'),
        ),
        body: SafeArea(
          child: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(24.0),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  Text(_file ?? 'Please select a file'),
                  Text(
                    (_mediaInfoCache?.keys ?? <String>[])
                        .map((String k) => '$k: ${_mediaInfoCache![k]}')
                        .join(',\n\n'),
                    style: Theme.of(context).textTheme.body2,
                  ),
                  Builder(
                    builder: (BuildContext context) {
                      if (_thumbnails.isEmpty) {
                        return const SizedBox();
                      }

                      final List<String> listW = _thumbnails.keys.toList();
                      listW.sort((a, b) {
                        final wA = int.parse(a.split('x').first);
                        final wB = int.parse(b.split('x').first);

                        return wA.compareTo(wB);
                      });

                      final List<Widget> widgets = <Widget>[];
                      for (final String res in listW) {
                        widgets.addAll([
                          Text(res),
                          FutureBuilder<String>(
                            future: _thumbnails[res],
                            builder: (BuildContext context, snapshot) {
                              if (snapshot.hasData) {
                                return Image.file(File(snapshot.data!));
                              }
                              if (snapshot.hasError) {
                                return Text(
                                  'E: ${snapshot.error}',
                                  style: TextStyle(color: Colors.red),
                                );
                              }

                              return const SizedBox();
                            },
                          ),
                          Divider(),
                        ]);
                      }

                      return Column(
                        mainAxisSize: MainAxisSize.min,
                        children: widgets,
                      );
                    },
                  ),
                ],
              ),
            ),
          ),
        ),
        floatingActionButton: _buildSelectButton(),
      ),
    );
  }

  Widget _buildSelectButton() {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        FloatingActionButton(
          key: Key("local file"),
          child: Icon(Icons.attach_file),
          onPressed: () async {
            final FilePickerResult? mediaFile =
                await FilePicker.platform.pickFiles();

            if (!mounted || mediaFile == null) {
              return;
            }

            setState(() {
              _file = mediaFile.files.single.path;
              _mediaInfoCache = null;
              _thumbnails.clear();
            });

            final Map<String, dynamic> mediaInfo =
                await _mediaInfo.getMediaInfo(_file!);

            if (!mounted || mediaInfo == null) {
              return;
            }

            setState(() {
              _mediaInfoCache = mediaInfo;
            });

            final Directory cacheDir = await getTemporaryDirectory();
            final int cacheName = _file.hashCode;

            final int w = mediaInfo['width'];
            final int h = mediaInfo['height'];

            final String mime = mediaInfo['mimeType'];
            if (mime.startsWith("video/")) {
              Set<Resolution> resolutions = Set();
              resolutions.addAll(_resolutions);
              resolutions.add(Resolution(w, h));

              for (final Resolution res in resolutions) {
                final String target =
                    File('${cacheDir.path}/$cacheName.${res.w}').path;
                if (File(target).existsSync()) {
                  File(target).deleteSync();
                }

                _thumbnails['${res.w}x${res.h}'] = _mediaInfo.generateThumbnail(
                  _file!,
                  target,
                  res.w,
                  res.h,
                  positionMs: 100,
                );
              }
            }

            setState(() {});
          },
        ),
        SizedBox(width: 24),
        FloatingActionButton(
          key: Key("remote file"),
          child: Icon(Icons.wifi),
          onPressed: () async {

            setState(() {
              _file = "remote file";
              _mediaInfoCache = null;
              _thumbnails.clear();
            });

            Set<Resolution> resolutions = Set();
            resolutions.add(Resolution(1280, 720));

            final Directory cacheDir = await getTemporaryDirectory();
            final int cacheName = _file.hashCode;

            for (final Resolution res in resolutions) {
              final String target =
                  File('${cacheDir.path}/$cacheName.${res.w}').path;
              if (File(target).existsSync()) {
                File(target).deleteSync();
              }

              _thumbnails['${res.w}x${res.h}'] = _mediaInfo.generateThumbnail(
                "https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4",
                target,
                res.w,
                res.h,
                positionMs: 5000,
              );
            }

            setState(() {});
          },
        ),
      ],
    );
  }
}

Download Details:

Author: ened

Source Code: https://github.com/ened/flutter_plugin_media_info

#flutter #media 

Determine Multimedia File Properties Like Width, Height, Duration
Lewis  Grady

Lewis Grady

1626945240

How to Create Social Media Buttons | HINDI

frnds,
Aaj ke is video me humlog banyeneg Social Media Buttons
Isme humlog sirf use krnege Font Awesoem 5

Social Media
Twitter https://twitter.com/toofani_coder
Instagram https://www.instagram.com/toofani_coder

#media #social #hindi

How to Create Social Media Buttons | HINDI