search
HomeWeb Front-endCSS TutorialShare the usage and example tutorials of Shrinktofit (adaptive width)

Adaptive width means that when the width of the container is not explicitly set (or Margins is set to auto), the width of the container will automatically change according to the situation under certain circumstances. Settings, and the results of setting are often not what we want.

The W3C specification describes several shrink-to-fit situations

  • ##10.3.5 Floating, non-replaced elements

  • 10.3.7 Absolutely positioned, non-replaced elements

  • ##10.3.8 Absolutely positioned, replaced elements
  • 10.6.4 Absolutely positioned, non-replaced elements
  • The specification mentions a basic concept, let’s take a look at it first.

replaced elements & non-replaced elements

CSS divides html elements into two categories: non-replaceable elements and replaceable elements.

  • 1. Replaceable elements

    :

  • In CSS, replaceable elements are elements whose presentation is not Controlled by CSS. The presentation of these external elements does not depend on CSS specifications. Typical replaceable elements include img, object, video and form elements such as textarea and input. Some elements, such as audio and canvas, are replaceable elements only in special circumstances. Objects inserted using the CSS content property are called anonymous replaceable elements.

  • 2. Non-replaceable elements

    :

  • Otherwise, it is a non-replaceable element.

After understanding the concept, let’s return to the topic. There are many situations of shrink-to-fit. Here is the most common situation, that is, adaptive width when non-replaceable elements are floating (Floating, non-replaced elements). It sounds a bit abstract, but you may encounter it often. . Let’s look at an example first:

html&css

<!DOCTYPE html>
<html>
    <style type="text/css">
        .outer {
            width: 800px;
            background: black;
            overflow: hidden;
        }
        .inner {
            float: left;
            background: red;
        }
        .sub1 {
            width: 26%;
            background: blue;
        }
        .sub2 {
            width: 50%;
            background: green;
        }
    </style>
<head>
</head>
<body>
    <p class="outer">
        <p class="inner">
            <p class="sub1">
                this is 1th line this is 2th line this is 3th line this is 4th line
            </p>
            <p class="sub2">
                sub2 block
            </p>

        </p>
    </p>
</body>
</html>

This style defines an outer container with a black background and a width of 800px. It also has an inner container inner, which has no width and floats left. , there are two small blocks sub1 and sub2 in the inner.

Then the question comes, what is the specific width of inner, sub1, sub2?

Look at the renderings first and then answer:

Share the usage and example tutorials of Shrinktofit (adaptive width)

The result should be beyond your expectation: inner The width of the (red background) is not the width of the outer (black background) (under normal circumstances it should be
inherited

the width of the parent container), so sub1 and sub2 are much smaller than we expected. Before answering this question, let’s try to modify it first to see if we can find the cause of this problem. After

debugging

, I found two simplest solutions to solve this problem:

  • 1. Add width to inner width: 100%;

  • #2. Cancel the floating of inner.

  • The result after the solution is as follows:

Share the usage and example tutorials of Shrinktofit (adaptive width)

This is indeed what we want Yes, but this cleverly avoids the situation of floating non-replaceable elements. To be honest, I have encountered this scenario many times, but I just tried using the above two solutions, but I didn’t know the real reason, so I took a look at the W3C specifications in this regard. The description of the specifications is as follows:

Share the usage and example tutorials of Shrinktofit (adaptive width)

First of all, the problem of not speaking in English, simply 'Roughly' and 'CSS 2.1 does not define the exact algorithm' It makes people laugh and cry, and then gives a shrink-to-fit formula:

min(max(preferred minimum width, available width), preferred width)

Hehe, but they are not the same. God knows how to calculate these three values.

I googled online and found that many people have encountered this problem, but they can’t understand the specifications. Some people have translated the above paragraph. You can take a look:

CSS2.1 does not provide the exact algorithm for preferred minimum width, available width and preferred width. Usually, the preferred width is calculated by forcing other parts of the content except for explicit line breaks to not wrap; on the contrary, try to wrap the content as much as possible. To get the preferred minimum width; available width is the width of the element's containing block minus 'margin-left', 'border-left-width', 'padding-left', 'padding-right', 'border-right-width ', the value of 'margin-right' and the width of any vertical scrollbar that exists.

Please raise your hands if you are confused by this translation. . . . . . . . . . . . .

Returning to the topic again, after nearly an hour of groping, I finally smoothed out this difficult English:

There are three parameters here, namely: preferred minimum width, available width, preferred width. You only need to care about the calculation method of preferred width. The calculation method of preferred width is as follows:

Let the element The maximum width after the content is forced not to wrap is the width after shrink-to-fit

Take the above example specifically, the content of sub1 in the inner is wrapped due to insufficient width, so it is forced not to wrap. The calculated width of the line break is the adaptive width of the inner (the inner itself does not have a set width~). How to force no line break is also very simple. Slowly increase the width of sub1, and you will find that when it is adjusted to 100%, it is just enough to use one line. To realize the content, the width of the content is the width after inner adaptation. Directly above the picture:

Share the usage and example tutorials of Shrinktofit (adaptive width)


#Summary:

For floating or special positioning methods, It is recommended to explicitly set the container width to avoid unexpected results

Please click here to view the original blog text

[Related recommendations]

1.

Freecssonlinevideotutorial

2.

css online manual

3.

php.cnDugujiujian (2)-css video tutorial

The above is the detailed content of Share the usage and example tutorials of Shrinktofit (adaptive width). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
A Little Reminder That Pseudo Elements are Children, Kinda.A Little Reminder That Pseudo Elements are Children, Kinda.Apr 19, 2025 am 11:39 AM

Here's a container with some child elements:

Menus with 'Dynamic Hit Areas'Menus with 'Dynamic Hit Areas'Apr 19, 2025 am 11:37 AM

Flyout menus! The second you need to implement a menu that uses a hover event to display more menu items, you're in tricky territory. For one, they should

Improving Video Accessibility with WebVTTImproving Video Accessibility with WebVTTApr 19, 2025 am 11:27 AM

"The power of the Web is in its universality. Access by everyone regardless of disability is an essential aspect."- Tim Berners-Lee

Weekly Platform News: CSS ::marker pseudo-element, pre-rendering web components, adding Webmention to your siteWeekly Platform News: CSS ::marker pseudo-element, pre-rendering web components, adding Webmention to your siteApr 19, 2025 am 11:25 AM

In this week's roundup: datepickers are giving keyboard users headaches, a new web component compiler that helps fight FOUC, we finally get our hands on styling list item markers, and four steps to getting webmentions on your site.

Making width and flexible items play nice togetherMaking width and flexible items play nice togetherApr 19, 2025 am 11:23 AM

The short answer: flex-shrink and flex-basis are probably what you’re lookin’ for.

Position Sticky and Table HeadersPosition Sticky and Table HeadersApr 19, 2025 am 11:21 AM

You can't position: sticky; a

Weekly Platform News: HTML Inspection in Search Console, Global Scope of Scripts, Babel env Adds defaults QueryWeekly Platform News: HTML Inspection in Search Console, Global Scope of Scripts, Babel env Adds defaults QueryApr 19, 2025 am 11:18 AM

In this week's look around the world of web platform news, Google Search Console makes it easier to view crawled markup, we learn that custom properties

IndieWeb and WebmentionsIndieWeb and WebmentionsApr 19, 2025 am 11:16 AM

The IndieWeb is a thing! They've got a conference coming up and everything. The New Yorker is even writing about it:

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.