📜 ⬆️ ⬇️

CSS weirdness to know about

Our publications regularly feature articles about CSS. Among them - material about the history of CSS , a story about the selection of names for CSS-entities, an article about CSS-styles for printing , which many people forget. We wrote about how CSS selectors work , comparing what is happening with the car dealership, about the relatively new CSS Grid Layout technology, and that CSS is not black magic . Today we bring to your attention the translation of material that is dedicated to the CSS strangeness, which, as the author of this material suggests, very few people know.

image

Vertical fields


What will happen to the element if you assign the padding-top: 50% property to it padding-top: 50% ? Intuitively, this property sets the size of the field from the top edge of the contents of the element, the size of which is 50% ... What does this 50% do? As a matter of fact, at a certain moment intuition turns out to be useless when analyzing the features of this property. The fact is that these 50% are taken from the width of the parent element of the element to which the top field is assigned.

Here is an example prepared by means of CodePen. Such examples can be found in many other sections of this material.
')
The same is true for the bottom field, which is specified by the padding-bottom property. Knowledge of this feature, in particular, allows you to create responsive elements that preserve the aspect ratio:

 .square { width: 100%; height: 0; padding-bottom: 100%; } 

About non-permanent collapse of indents


The distance between the following elements will be 20px , not 40px :

 <div style="margin-bottom:20px">foo</div> <div style="margin-top:20px">foo</div> 

→ Example

However, this is not always the case. Indentations do not collapse when working with the following elements:


The level of transparency and the order of blending elements


Suppose there are three <div> elements, each of which is absolutely positioned. They contain other elements that are assigned a z-index property with values ​​from 1 to 3. Each next such element is displayed on top of the previous one. If you now assign the z-index: 10 to the lowest element, it will be displayed on top of the other two, the order of which will not change. So far, everything looks as expected. If you now assign the first element <div> , the one that is now above the others, the opacity: 0.99 property, it will be under the other two.

→ Example

Details on why this happens can be found here .

Custom CSS Properties and Variables


Using SASS or LESS, you can decide that custom properties and CSS variables are equivalent to the features available in these preprocessors. However, there are several differences that are worth paying attention to.

First, consider the basics:

 //        :root { --foo: #000; } button { background-color: var(--foo); //  } 

Custom properties, moreover, are inheritable, that is, if you reassign a local variable, this will affect all descendant elements, and, unlike the preprocessor, the browser, when this happens, recounts all expressions where such variables are used.

When using custom properties, backup values ​​can be listed separated by commas. The list of reserve values ​​may include other variables.

 .foo { color: var(—-my-var, 'blue'); } 

This leads us to the main difference with preprocessors: CSS variables are aware of the structure of the DOM and the changes that occur there.

 ::root { --default-color: #000000; } header { --primary-color: #ff0000; } a { color: var(--primary-color, --default-color); } <a href="">this is black</a> <header> <a href="">this is red.</a> </header> 

Unlike the first example that demonstrates inheritance, this example relies on backup values ​​that are affected by whether a custom property has been set in the parent DOM element or not.

→ Example

Moreover, they can be easily changed using JavaScript tools:

 //    inline- element.style.getPropertyValue("--my-var"); //    inline- element.style.setProperty("--my-var", jsVar + 4); 

This feature is supported since Edge 15.

Construction vertical align: top | middle | bottom


Construction vertical align: top | middle | bottom vertical align: top | middle | bottom vertical align: top | middle | bottom works only for inline elements (including inline-block ) and table-cell elements. This method is not suitable for aligning elements within their parent elements. To do this, you need to use the flexbox layout tool, or what is known as “douchebag vertical align” (we’ll talk about it below).

The height property: 100% may not have the expected effect.


What we talked about in the previous section is also true for the height: 100% property height: 100% . In many cases, setting this property does not lead to what the developer expects. The reason for this lies in the fact that the height of the parent element is not specified. Consider an example:

 <html> <body> <div style="height:100%;background:red;"></div> </body> </html> 

The <div> element shown here will not fill the entire page in red. To achieve this, you need to set the height property to 100% for both the <body> element and the <html> element.

ID styles and class styles


Identifier styles override styles defined at the class level. This happens because id selectors are more accurate than class selectors. So, for example, the rule specified for .foo.bar override the rules set separately for .foo and for .bar .

 #foo { color: red; } .bar { color: green; } <h1 id="foo" class="bar">this will be red not green</h1> 

Selection of elements with a specific attribute


Using CSS tools, you can select elements based on specific attributes and their contents. For example, it may be the contents of the src or href attributes.

 //     zip- (  ) a[href$=".zip" i] { } //     google.com [href*="google.com"] { color: red; } 

This technique may be useful when debugging, for example, to select all img elements with an empty alt attribute:

 img:not([alt]) { border: 2px dashed red; } img[alt=""] { border: 2px dashed red; } 

If you are using Angular, this approach can also be useful for selecting items that contain [ng-click] . Or, if necessary, you can visually separate links to local resources, and links that begin with http or https .

→ Example

On the sequence of properties when specifying the values ​​of parameters horizontally and vertically


When some values ​​are specified that relate to the horizontal and vertical axes, the first number usually sets the vertical value, and the second number the horizontal value. For example, in the expression padding: 10px 20px; 10px padding: 10px 20px; 10px is the top and bottom 20px , 20px is the right and left margins. This is what it looks like when setting up margins, indents, borders, in general - this is true for almost everything, with the exception of the border-spacing in tables where values ​​are arranged exactly the opposite: the first number sets the value horizontally, the second - vertically.

Multiple background images for a single item


The same element can be assigned several background images, separated by a comma. In addition, each of them can be configured in different ways, for example - positioned.

 background: url(example1.png') no-repeat center 50px, url('example2.jpg') no-repeat bottom top; 

This feature is supported starting with IE11.

CSS animation overlay


Just like when working with backgrounds, you can overlay CSS animations:

 @keyframes foo { 0% { opacity: 0; } 100% { opacity: 1; } } @keyframes bar { 0% { transform: translateX(-100px); } 100% { transform: translateX(0px); } } .element { animation: foo 2s 0s, bar 1s 0s; } 

About strange behavior position: fixed when using translateZ transform


Transformation add translateZ(0); to a container that includes an element with the property position: fixed; aligns the element with the container, rather than with the window.

→ Example

Stylization of elements to which the transition to the addresses containing the grid character (/ # foo)


The pseudo-class :target can be used to style the elements to which the transition is made when clicking on a link with a grid symbol. For example, clicking on a link like <a href="#foo">Go to Foo</a> scroll the page to the element <div id="foo">foo</div> . Now, if you included in the CSS a rule like #foo:target { color: red; } #foo:target { color: red; } , the <div> #foo will be colored red.

Selecting such elements can be useful for those site visitors who hit the page through an external link like www.example.com/#foo . With this approach, the browser scrolls the page to the desired element and this element will be highlighted. Nowadays they rarely do this, but this technique can improve the user experience of working with the site.

→ Example

Some known content features: 'foo';


â–Ť Data Attributes


Data attributes can be used for dynamic CSS content. For example:

 <div data-text="foo"></div> div:before { content: attr(data-text); } 

→ Example

This technique can be useful if, for example, you need to translate the text of a pseudo-class (for example, using it for tooltips). Now with the help of attr() you can only work with content. Although it is possible the emergence of support for this design other properties. Moreover, the values ​​obtained from attr() are strings, so they are intended primarily for content and cannot be used for size properties (for example, font-size ) or for links (for example, content: url() ) By the way, let's talk about it.

TentContent: url ()


This design can be used for many types of data (images, sounds, video). For example:

 <div></div> div:before { content: url(image.jpg); } 

→ Example

However, if you need to pass arbitrary data from the DOM to CSS, you will have to refer to the above custom properties:

 <div style="--background-image: url('http://via.placeholder.com/150x150');"></div> div:after { content: ''; background-image: var(--background-image); } 

â–Ť Incremental counter


The content: counter() construct can be used for incremental pseudo-element numbering:

 p { counter-increment: myIndex; } p:before { content:counter(myIndex); } <p>foo</p> <p>bar</p> 

→ Example

â–ŤUsing and closing quotes


The content property of pseudo classes like :before and :after can be used to add opening and closing quotes to elements:

 q:before { content: open-quote; } q:after { content: close-quote; } 

If we talk about quotes, then combining this technique with the previously mentioned selection of data attributes, you can even use CSS to set a specific localized style of quotes based on the site language, using only the quotes property:

 html[lang="fr"] q { Quotes: "«" "»"; } 

Using the font property


The font property allows, in an abbreviated format, to set font parameters:

 h1 { font-weight: bold; font-style: italic; font-size: 1rem; //etc… } //   h1 { font: italic lighter 1rem/150% Verdana, Helvetica, sans-serif; } //  // font: font-style font-variant font-weight font-size/line-height font-family; 

Supports directive


The @supports directive can be used to check if the browser supports features of interest to the developer. Let's say if display:flex is planned to be used only if there is confidence in the browser support for this feature, you can apply the following construction:

 @supports (display: flex) { div {  display: flex; } } 

Colons in Class Names


The use of colons in class names can be useful for creating clearer names that, when read, are easier to divide into parts. For example, some CSS UI frameworks (like Tailwind ) use the following naming conventions:

 <div class="justify-start sm:justify-center md:justify-end lg:justify-between xl:justify-around"> <button class="bg-blue hover:bg-blue-dark text-white hover:text-blue-light">Button</button> 

Specifying specific classes for styles applied to elements over which the mouse pointer is located may not be particularly useful in most cases, but this approach allows us to clearly distinguish the corresponding states from others, which improves the readability of the code.

To use colons in CSS, they need to be escaped:

 .sm\:justify-center { } 

Three element selector


Everyone who reads this material should know about the three-element CSS selector, commonly called “ lobotomized owl selector ”. Here is what it looks like:

 * + * { margin-top: 2rem; } 

It will be necessary by the way in situations when there are many elements of one type, between which there should be an indent, and, after the last element of such a list, the indent is not needed:

 li + li { margin-top: 1rem; } //  li { margin-bottom: 1rem; } li:last-of-type { margin-bottom: 0; } 

Vertical alignment using the “douchebag vertical align” method


Since we are talking about unusual selectors, let’s recall the vertical alignment technique called “douchebag vertical align”:

 .element { position: relative; top: 50%; transform: translateY(-50%); } 

The font-feature-settings property for OpenType fonts


OpenType fonts support setting properties. This feature can be used to fit the font to the needs of a particular project due to the font-feature-settings property.

One of the options for using this feature opens up in a situation where you need a beautiful font that is not monospaced for a countdown timer. Without special adjustment the width of the sequence of numbers will constantly change. It looks unprofessional. Here is the solution to this problem:

 font-feature-settings: "tnum"; font-variant-numeric: tabular-nums; 

Crop text with the addition of the end in the form of ellipsis, "..."


It's all very simple:

 p { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } 

→ Example

Results


We looked at some obscure CSS features that we hope will be useful for web developers. By the way, here's another interesting thing, not related, however, to CSS. This is a wbr HTML element that allows you to mark the location of word breaks.

Dear readers! Do you know of any CSS features that are useful, but not widely known?

Source: https://habr.com/ru/post/350658/


All Articles