All HTML required to display SVG flags is:
FlagMeister is a single KB gzip Custom Element / Web Component file
FlagMeister was developed in 2018 using ‘Customized Built-In’ Elements: <img is=flag-nl />
Alas Apple still refuses to implement this part of the Web Components standard in Safari.
In 2020 FlagMeister switched to slightly more verbose, but 100% supported ‘Autonomous’ Elements: <flag-nl></flag-nl>
If all you want is a SVG flag you can stop reading here.
Read on if you want FlagMeister to create:
Draw SVG on flags
The draw attribute/property accepts any valid SVG string or FlagMeister commands and adds it on top of the FlagMeister flag (a 640 x 480 grid)
FlagMeister commands and parameters (to be documented)
- backgroundcolor bgcolor: or b: [color = #fff]
- circle circle: or c: cx , cy , radius , color [, stroke width , strokecolor]
- rect: x , y , width , height , color , [stroke width , strokecolor]
- line: width , color , x1 , y1 , x2 , y2 , [stroke width , strokecolor]
- flag: iso , [stroke width , strokecolor]
- background: color
- attr: attribute , fontsize , y OR attr: text-JSON
- text: JSON Object: (showing default values):
Notes on drawing
- FlagMeister does no error checking, pay attention to single and double quote usage
- SVG strings can only contain single quotes
- The FlagMeister text method takes one parameter, a valid JSON string with double quotes
- Be sure to read what you are NOT allowed to do with the US flag by US Federal code 36
Apply CSS on IMGs
The FlagMeister flag IMG takes 100% of available width , in examples below the 5 column CSS grid sets the width.
FlagMeister generates SVG as Data-URI in IMG tags. All examples use standard CSS on the IMG tag :
Clip flags
Change SVG viewBox = » x y width height «
The flag is still drawn in a 640 by 480 grid !
Apply the FlagMeister light filter
This predefined SVG filter creates a 3D lighting effect and an optional spotlight defaulting to the center of the flag
The FlagMeister light function takes optional parameters as a JSON-formatted string in the filter attribute:
or , after deep-learning SVG filters, paste any valid SVG filter definition in the filter attribute.
CSS custom properties/variables can style multiple flags
FlagMeister flags redraw on attributes changes (observedAttributes): draw , clip , box , filter
Flags are not updated when CSS variables change!
When you hover (onmouseover) the 4th and 5th heart, the —flagmeisterfilter is not applied!
Use the flag.load() method to redraw a flag OR trigger an attribute change.
You can now re-create the banner:
- Word: yes! this is a live INPUT field (use a _ underscore for spaces)
- an flag image for every letter
- Clipped with a SVG text-character
- FlagMeister Light filter
- CSS highlighting and drop shadow
But that is too much work.
. the FlagMeister added 361 BYTES!
. Now. you create the banner with a Autonomous Custom Element :
flagmeister-text creates all child DOM elements.
There is no shadowDOM so you can customize all elements with CSS specificity
Ofcourse it is impossible to store all flag details in 22 KB
IF flags require more detail
FlagMeister loads flags async when the width exceeds a number of pixels (observed by the ResizeObserver API)
Note: See the Flag Analyzer below which flags load extra detail by default
SVG flag repositories:
Observations
- The countries API (used by default) does not have a detailed Bolivian flag
- Most repos use the true size (not 640:480) flagsize (you can ofcourse force height with CSS)
- The very popular Lipis repo almost always has flags with incorrect colors
detail and source parameters
Detail loading (n pixels) and the source repo can be configured with an element attribute/property OR CSS variable
Prevent detail loading (unless flag img is over 9998 pixels wide) Load from Nilsson Repo Load detail flags from Kent Repo No detail specified, so only flags with default detail setting Load all flags from Kent Repo (forced detail loading for every image over 1 pixel wide)
I built this tool for my flag selection phase, never meant it to be part of this demo page.
It is too cool to go to waste. But don’t move the mouse too fast!
Repo | GitHub used / stars / fork 2018 count |
Flags | Requests | All Flags GZip size |
https://flags.dsgn.it/ Great UI! But can’t load with 2-letter ISO reference |
0 / 3 / 0 | 250+ Also regional flags |
1 per SVG flag file | > 660 KB |
RestCountries API | 579 / 4439 / 968 | 251 | 2 per SVG flag file Requires first call to API, returns the flag URI |
> 660 KB |
Lipis flag-icons Popular, But. most flags have wrong colors |
9161 / 5920 / 832 | 247 | 1 per SVG flag file | 687 KB |
Nillson | 175 / 1440 / 281 | 257 | 1 per SVG flag file | 1100 KB |
Kent1D Flags in true proportions (not 4:3) |
0 / 8 / 1 | 254 + regional, org. and historical flags |
1 per SVG flag file | est. 600 KB |
Phocas SVG as CSS background |
No Github Repo | 253 | 1 CSS file | 1297 KB |
FlagMeister JavaScript generated SVG |
1 / 1 / 1 | 250+ flags | 1 JavaScript file | 21 KB |
All FlagMeister flags needing work Flags with detail Mismatching flags > 1 KB flags —> Filter:
Almost all colors in the Lipis Repo are incorrect, these are just the obvious ones.
Create a Flag With CSS
Join the DZone community and get the full member experience.
Corner flags are a nice way of labelling an image to emphasise something is ‘new’, ‘featured’ or ‘on offer’. Often these effects are done with images. This tutorial gives an example of how to achieve this using CSS and semantic HTML.
Example HTML
Our markup is straightforward and semantic. Requiring two elements: one for the corner flag and the other for the text.
The flag is positioned absolutely so just needs to be contained to achieve the correct results.
Example Code
Published at DZone with permission of $$anonymous$$ , DZone MVB . See the original article here.
I made all countries' flags using HTML & CSS
I am starting a new series called CSS Flag. Where I'll be making different countries' flags starting with India.
I asked myself "Why don't I make an article which will have all 195 countries' flags instead of creating 195 articles?". Well, Here I am.
In this article, I have made all countries' flags by just using HTML and CSS. At the end of the article. You will have a special Bonus (you have to reach the end of the article to see it).
Создаем развевающийся флаг на CSS
Сегодня у нас дело государственной важности, господа! Нам выпала честь создать анимацию — флаг на CSS. Да не всякий флаг требуется сотворить нашими руками, а именно триколор! Двухцветный флаг, кстати, мы также научимся делать по мотивам триколора. В основе создания анимации флага будет лежать принцип, описанный в предыдущей статье «Эффект волны на CSS». Итак, закатаем рукава повыше и приступим к созданию флага на CSS! Предлагаю начать с создания российского флага. Для получения иных триколоров по описанному ниже методу, потребуется лишь заменить цвета флага на нужные. В каких местах нужно будет внести изменения, я укажу в тексте статьи. Для начала сформулируем задачу:
Цель: создать анимацию развевающегося российского флага по примеру изображения в начале статьи.
Инструменты: HTML, CSS
Принцип создания анимации флага
Основной принцип заключается в задании вращения скругленным блокам, окрашенным в цвета флага. Так как блоки будут увеличены не менее, чем в 2 раза по отношению к фоновому кругу, а фоновому кругу мы зададим свойство overflow:hidden, то пользователь увидит лишь часть анимации. Увиденный фрагмент анимации будет создавать иллюзию развевающегося флага.
Приступаем к созданию кода
1. Для начала откроем HTML-файл и добавим в него фоновый блок с идентификатором «flag». Этот блок я планирую закрасить в белый цвет, чтобы из верхней части сформировать белую полосу флага. Внутри фонового блока расположим блоки с классами «wave2» и «wave3» для синей и красной полосы соответственно:
2. После этого добавим стили для вновь созданных блоков в CSS-файл. Для фонового блока определим белый background, зададим размеры, отступы, закругление. Кроме того, добавим свойство overflow: hidden, которое обрежет выходящие за пределы этого блока части других элементов:
Позиционируем элементы с классами «wave2» и «wave3» так, чтобы селектор «.wave2» оказался расположен выше селектора «wave3». После этого увеличим размеры блоков до 200%, закруглим края и окрасим их в синий и красный цвета. В заключение присвоим этим блокам анимацию под названием «wave», которую опишем ниже:
Настало время оживить наши блоки! Для этого опишем анимацию «wave» — зададим блокам вращение на 360 градусов:
Осталось сохранить изменения в файлах и обновить страницу в браузере. Анимация российского флага выполнена успешно!
Думаю, вы догадались, что нужно сделать для превращения российского триколора в триколор другой страны. Для этого нужно задать селекторам «#flag», «.wave2» и «.wave3» другие значения для свойства background. Например, для превращения российского флага в габонский, я поменяла значение свойства background-color для селектора #flag на зеленый цвет #4e9f61:
Для селекторов .wave2 и .wave3 изменим фоновые цвета на желтый и синий соответственно :
В итоге у меня получился симпатичный габонский флаг:
3 комментария
Если я просто переписываю код,у меня выходит только два цвета-синий и белый,скопированный вставляю,то все три.Почему так?Проверила все до каждой запятой,все равно красный не выходит на переписанном,только на скопированном.