- data inside box in html code example
- Example 1: how to style rule to apply the Border Box model css
- Example 2: css box model
- Example 3: css box model
- Использование data-* атрибутов
- Синтаксис HTML
- Доступ в JavaScript
- Доступ в CSS
- Проблемы
- Смотрите также
- Found a content problem with this page?
- A Complete Guide to Data Attributes
- Desktop
- Mobile / Tablet
data inside box in html code example
Example 1: how to style rule to apply the Border Box model css
header, ul, nav, li, a /* other elements */ display: block; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box;
Example 2: css box model
/********************** CONTENT ************************* The box that contains the actual element content like text, image, icon, gif, video. */ tag_name height: 90px; width: 200px; > /********************** PADDING ************************* Distance between the content and the border. The background color, of the element will never affect this space. But you can see this by contrasting with the background color of the parent element that contains your element*/ tag_name padding-top: 50px; padding-right: 30px; padding-bottom: 50px; padding-left: 80px; > /*OR: */ tag_name padding: 25px 50px 75px 100px; /* top; right; bottom; left */ > tag_name padding: 25px 50px 75px; /* top; right_&_left; bottom */ > tag_name padding: 25px 50px; /* top_&_bottom; right_&_left */ > tag_name padding: 25px; /* top_&_bottom_&_right_&_left */ > /********************** BORDER ************************* You can define a frame for your element's box. You can only see the border, after you define a style for that property */ tag_name border-width: 5px 70px 10px 28px; /* or border-bottom-width: 10px; . */ border-color: blue; /* or border-top-color: #b52e2e; . */ border-style: dotted; /* or dashed, or solid, or . */ border-radius: 70% /* making the corners more rounded */ > /*OR: */ tag_name border: 5px solid red; /* all_widths; style; color */ > tag_name border-left: 6px dotted green; /* width; style; color */ border-top: 34px groove yellow; /* width; style; color */ > /********************** OUTLINE ************************* It's a line that's drawn around your html element, but contrary to the border, the dimensions of the outline aren't taken into account. It's drawn around elements, outside the borders, to make the element "stand out" */ tag_name outline-width: thin; /* or medium; thick; outline-width: 4px; . */ outline-color: blue; /* or #b52e2e; invert; . */ outline-style: dotted; /* or dashed, or solid, or . */ outline-offset: /* making the corners more rounded */ > /*OR: */ tag_name outline: dashed; > tag_name outline: dotted red; > tag_name outline: 5px solid yellow; /* all_widths; style; color */ > tag_name outline: thick ridge pink; > /********************** MARGIN ************************* This is the distance that separates an html element, from the other elements around it. The background color, of the element will never afect this space, because the margin doesn't have background color. The margin is an invisible border or space between two objects */ tag_name margin-top: 100px; margin-bottom: 100px; margin-right: 150px; margin-left: 80px; > /*OR: */ tag_name margin: 25px 50px 75px 100px; /* top; right; bottom; left */ > tag_name margin: 25px 50px 75px; /* top; right_&_left; bottom */ > tag_name margin: 25px 50px; /* top_&_bottom; right_&_left */ > tag_name margin: 25px; /* top_&_bottom_&_right_&_left */ >
Example 3: css box model
MDN (Mozilla Developer Network) Probably the best place for an in-depth explanation of web related technologies. See the link below regarding the CSS BOX MODEL
Использование data-* атрибутов
HTML5 (en-US) спроектирован с возможностью расширения данных ассоциированных с каким-либо элементом, но в то же время не обязательно имеющих определённое значение. data-* атрибуты позволяют хранить дополнительную информацию в стандартных элементах HTML, без хаков вроде нестандартных атрибутов, лишних DOM-свойств или Node.setUserData() .
Синтаксис HTML
Синтаксис прост — любой атрибут, чьё имя начинается с data- , является data-* атрибутом. Предположим у нас имеется статья и мы хотим сохранить дополнительную информацию без визуального представления. Для этого можно использовать data -атрибуты:
article id="electriccars" data-columns="3" data-index-number="12314" data-parent="cars"> . article>
Доступ в JavaScript
Чтение data- атрибутов в JavaScript осуществляется также просто. Для этого можно использовать метод getAttribute() с параметром, равным полному имени атрибута. Но есть и более простой способ, используя объект dataset (en-US).
Чтобы получить data -атрибут можно взять свойство объекта dataset с именем, равным части имени атрибута после data- (обратите внимание, что дефисы в имени преобразуются в camelCase).
var article = document.getElementById('electriccars'); article.dataset.columns // "3" article.dataset.indexNumber // "12314" article.dataset.parent // "cars"
Каждое свойство является строкой и может быть прочитано и записано. В приведённом выше примере выполнение кода article.dataset.columns = 5 приведёт к тому, что новое значение атрибута станет равным «5» .
Доступ в CSS
Заметим, что data -атрибуты являются обычными HTML-атрибутами, к которым можно получить доступ в CSS. Например, чтобы показать родительские данные о статье можно использовать генерируемый контент и CSS функцию attr() :
article::before content: attr(data-parent); >
Также можно использовать селекторы атрибутов в CSS для изменения стилей в соответствии с данным:
article[data-columns='3'] width: 400px; > article[data-columns='4'] width: 600px; >
Увидеть как это работает можно в примере на JSBin.
Data -атрибуты также могут использоваться для хранения информации, которая постоянно изменяется, например, счёт в игре. Используя CSS селекторы и возможности JavaScript можно создавать некоторые изящные эффекты, без необходимости писать свои функции отображения. Посмотрите скринкаст чтобы увидеть больше примеров использующих сгенерированный контент и переходы на CSS. Пример кода из скринкаста можно также посмотреть на JSBin.
Проблемы
Не храните данные, которые должны быть видимы и доступны в data -атрибутах. Дело в том, что вспомогательная техника (assistive technology) может не получить к ним доступ. В дополнение, поисковые роботы не индексируют данные, содержащиеся в data -атрибутах.
Печально, что всё простое и полезное в этой жизни не достаётся бесплатно. Internet Explorer 11+ поддерживает этот стандарт, но все более ранние версии не поддерживают dataset . Для поддержки IE 10 и более ранних версий получение доступа к data -атрибутам необходимо осуществлять через getAttribute() . Также, производительность чтения data- атрибутов по сравнению с хранением этих данных в хранилище данных JS значительно хуже. Использование dataset ещё медленнее, чем чтение данных с getAttribute() .
Тем не менее, для пользовательских метаданных, связанных с элементами, data- атрибуты являются отличным решением.
Смотрите также
Found a content problem with this page?
This page was last modified on 7 нояб. 2022 г. by MDN contributors.
A Complete Guide to Data Attributes
HTML elements can have attributes on them that are used for anything from accessibility information to stylistic control.
What is discouraged is making up your own attributes, or repurposing existing attributes for unrelated functionality.
There are a variety of reasons this is bad. Your HTML becomes invalid, which may not have any actual negative consequences, but robs you of that warm fuzzy valid HTML feeling. The most compelling reason is that HTML is a living language and just because attributes and values that don’t do anything today doesn’t mean they never will.
Good news though: you can make up your own attributes. You just need to prefix them with data-* and then you’re free to do what you please!
It can be awfully handy to be able to make up your own HTML attributes and put your own information inside them. Fortunately, you can! That’s exactly what data attributes are. They are like this:
Data attributes are often referred to as data-* attributes, as they are always formatted like that. The word data , then a dash — , then other text you can make up.
Can you use the data attribute alone?
It’s probably not going to hurt anything, but you won’t get the JavaScript API we’ll cover later in this guide. You’re essentially making up an attribute for yourself, which as I mentioned in the intro, is discouraged.
What not to do with data attributes
Store content that should be accessible. If the content should be seen or read on a page, don’t only put them in data attributes, but make sure that content is in the HTML content somewhere.
Styling with data attributes
/* Select any element with this data attribute and value */ [data-size="large"] < padding: 2rem; font-size: 125%; >/* You can scope it to an element or class or anything else */ button[data-type="download"] < >.card[data-pad="extra"]
This can be compelling. The predominant styling hooks in HTML/CSS are classes, and while classes are great (they have medium specificity and nice JavaScript methods via classList ) an element either has it or it doesn’t (essentially on or off). With data-* attributes, you get that on/off ability plus the ability to select based on the value it has at the same specificity level.
/* Selects if the attribute is present at all */ [data-size] < >/* Selects if the attribute has a particular value */ [data-state="open"], [aria-expanded="true"] < >/* "Starts with" selector, meaning this would match "3" or anything starting with 3, like "3.14" */ [data-version^="3"] < >/* "Contains" meaning if the value has the string anywhere inside it */ [data-company*="google"]
The specificity of attribute selectors
It’s the exact same as a class. We often think of specificity as a four-part value:
inline style, IDs, classes/attributes, tags
So a single attribute selector alone is 0, 0, 1, 0. A selector like this:
…would be 0, 0, 2, 1. The 2 is because there is one class ( .card ) and one attribute ( [data-foo=»bar»] ), and the 1 is because there is one tag ( div ).
Attribute selectors have less specificity than an ID, more than an element/tag, and the same as a class.
Case-insensitive attribute values
In case you’re needing to correct for possible capitalization inconsistencies in your data attributes, the attribute selector has a case-insensitive variant for that.
/* Will match */ [data-state="open" i]
It’s the little i within the bracketed selector.
Using data attributes visually
CSS allows you to yank out the data attribute value and display it if you need to.
You could use data attributes to specify how many columns you want a grid container to have.
Accessing data attributes in JavaScript
Like any other attribute, you can access the value with the generic method getAttribute .
let value = el.getAttribute("data-state"); // You can set the value as well. // Returns data-state="collapsed" el.setAttribute("data-state", "collapsed");
But data attributes have their own special API as well. Say you have an element with multiple data attributes (which is totally fine):
If you have a reference to that element, you can set and get the attributes like:
// Get span.dataset.info; // 123 span.dataset.index; // 2 // Set span.dataset.prefix = "Mr. "; span.dataset.emojiIcon = "🎪";
Note the camelCase usage on the last line there. It automatically converts kebab-style attributes in HTML, like data-this-little-piggy , to camelCase style in JavaScript, like dataThisLittlePiggy .
This API is arguably not quite as nice as classList with the clear add , remove , toggle , and replace methods, but it’s better than nothing.
You have access to inline datasets as well:
JSON data inside data attributes
Hey, why not? It’s just a string and it’s possible to format it as valid JSON (mind the quotes and such). You can yank that data and parse it as needed.
const el = document.querySelector("li"); let json = el.dataset.person; let data = JSON.parse(json); console.log(data.name); // Chris Coyier console.log(data.job); // Web Person
The concept is that you can use data attributes to put information in HTML that JavaScript may need access to do certain things.
A common one would have to do with database functionality. Say you have a “Like” button:
That button could have a click handler on it which performs an Ajax request to the server to increment the number of likes in a database on click. It knows which record to update because it gets it from the data attribute.
This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.