CSS shapes layout tutorial written for yourself

CSS shapes layout tutorial written for yourself

This article was published on Saturday, February 2, 2019, at 22:47 and is classified as  CSS related . Read 24509 times, 1 today  7 comments

by  zhangxinxu  from  https://www.zhangxinxu.com/wordpress/?p=8453
This article can be reproduced in full. Personal website does not require authorization, as long as the original author, source and link in the article are retained. Any website can be summarized and used for commercial purposes. Contact authorization.

1. Preface & Index

The CSS Shapes layout can achieve irregular text wrapping effects, which need to be used in conjunction with floating.

The compatibility is as follows:

Surround layout compatibility

It is still very good, mobile terminal is available, internal middle and back-end projects are available.

There are not many attributes related to CSS shapes layout, and the learning cost is much smaller than grid layout and flex layout.

Shapes layout related attributes

2. Learn more about shape-outside

shape-outsideIt is the core of the irregular shape surround layout, and the supported attribute values ​​are divided into the following four categories:

  1. none-default value
  2. <shape-box> – Shape box.
  3. <basic-shape>-Basic shape function.
  4. <image>-Image category.

among them:

  • noneIt is easy to understand, it means that it is surrounded by an ordinary rectangle.
  • <shape-box>(Graphic box) is a term associated layout shape than clip-pathattribute <geometry-box>(geometry box) support box to be less, the box is four kinds of basic box model in CSS2.1, are margin-box, border-box, padding-boxand content-box. When you want to specify the text wrapping, it is calculated according to which edge of the box.
  • <basic-shape>It refers to the basic shape function, which is exactly the same as the basic shape function supported by the CSS  clip-path clipping property .
  • <image>The value is the image class, including URL link images, gradient images, cross-fade() , element(), etc. All these image classes are also supported by the CSS3 mask mask property . This article will only introduce commonly used URL links and gradient images. Other image classes will not be introduced. If you are interested, you can visit this article about masking , which is fully displayed.

The use of different types of attribute values ​​(taken from MDN ):

/* Keyword value*/
shape-outside: none;
shape-outside: margin-box;
shape-outside: content-box;
shape-outside: border-box;
shape-outside: padding-box;

/* Function value*/
shape-outside: circle();
shape-outside: ellipse();
shape-outside: inset(10px 10px 10px 10px);
shape-outside: polygon(10px 10px, 20px 20px, 30px 30px);

/* <url>value*/
shape-outside: url(image.png);

/* Gradient value*/
shape-outside: linear-gradient(45deg, rgba(255, 255, 255, 0) 150px, red 150px);

We quickly understand the role and performance of each type of attribute value through an example.

1. Keyword attribute value

The test HTML and CSS code are as follows:

<span class="shape"></span>
<p>Before CSS Shapes came out...</p>
.shape {
    float: left;
    width: 60px; height: 60px;
    padding: 10px; margin: 10px;
    border: 10px solid;
    border-radius: 50%;
    background-color: currentColor;
    background-clip: content-box;
    color: #cd0000;
    shape-outside: none;  /* 或margin-box,border-box,padding-box,content-box */
}

The resulting layout is shown as a GIF screenshot:

Surround performance of different keyword attribute values

It can be seen that when the shape-outsideattribute value noneis a keyword other than that, even ordinary border-radiusrounded corners can achieve the wrapping effect.

Seeing is believing, you can click here: CSS shape-outside keyword attribute value test demo

2. Basic shape functions

Refers to the following four basic shape functions:

  • circle() – circle
  • ellipse()-ellipse
  • inset()-inner rectangle (including rounded rectangle)
  • polygon()-polygon

among them:

circle()-circle The
syntax is as follows:

circle( [<shape-radius>]? [at <position>]? )

The question mark ?is a special character in regular expressions, which means 0sum 1, that is to say shape-radius(circle radius) and position(circle center position) can be defaulted. Therefore, the following writing is legal:

shape-outside: circle();
shape-outside: circle(50%);
shape-outside: circle(at 50% 50%);
shape-outside: circle(50% at 50% 50%);
shape-outside: circle(50px at 50px 50px);

A surround effect similar to the following figure can be achieved:

Circle surround effect

border-radiusCompared with the circular surround realized by adding the keyword attribute value , circle()the realization is relatively more flexible. For example, if you want to create a semicircular surround effect, you can:

shape-outside: circle(50% at 0% 50%);

The result is shown below:

Half circle surround effect

ellipse()-ellipse

The syntax is as follows:

ellipse( [<shape-radius>{2}]? [at <position>]? )

The x-axis radius, the y-axis radius, and the center position of the ellipse. The following are all legal:

shape-outside: ellipse();
shape-outside: ellipse(50px 75px);
shape-outside: ellipse(at 50% 50%);
shape-outside: ellipse(50px 75px at 50% 50%);

x, y radius of particular value in addition, supports farthest-sideand closest-sidetwo keywords, by definition, to indicate the length of the longest side and the length of the shortest side. E.g:

ellipse(farthest-side closest-side at 25% 25%)

Indicates that at the 25% 25%position of the floating element , the distance from the longest side of the floating element is used as the x coordinate of the ellipse, and the shortest distance from the edge of the floating element is used as the y coordinate of the ellipse. So, there is the following renderings (the size of the floating element is 100*100, the red dot is the 25% 25%position, and the outline of the ellipse can be seen):

Longest side and shortest side effects

If we change the order, take the shortest side as the x-axis and the longest side as the y-axis:

ellipse(closest-side farthest-side at 25% 25%)

The final performance is as follows:

Shortest side and longest side effects

Careful observation, not difficult to understand farthest-sideand closest-sidemean.

inset()-inner rectangle (including rounded rectangle)

The syntax is as follows:

inset( <shape-arg>{1,4} [round <border-radius>]? )

Among them shape-argare required parameters, which can be 1~4 values. When all the first four parameters are provided, they represent the top, right, bottom, and left offsets from the reference frame inward, that is, they define the edge position of the inserted rectangle. These parameters follow the syntax of margin abbreviations (similar margin, paddingetc. attributes), we can use 1, 2, 3 or 4 values. border-radiusIndicates the size of the fillet, which can be defaulted.

Therefore, the following writing methods are legal:

shape-outside: inset(10px);
shape-outside: inset(10px 20px);
shape-outside: inset(10px 20px 30px);
shape-outside: inset(10px 20px 30px 40px);
shape-outside: inset(10px 20px 30px 40px round 10px);

For example, the effect of the last line of code above is:
Inner rounded rectangle effect

The console view element box can see:

Round corner surround effect

polygon()-polygon

polygon()Polygons are the best understood syntax:

polygon( [<fill-rule>,]? [<shape-arg> <shape-arg>]# )

fill-ruleRepresents the filling rule, which can be nonzeroas well as the evenodddefault value nonzero. These two filling rules are the basic knowledge that must be mastered in the graphics field. You can refer to my previous article " Understanding the nonzero and evenodd filling rules in SVG/Canvas " for learning.

The scene polygonusage is:

polygon( x1 y1, x2 y2, x3 y3, ... )

It is the point coordinates of a polygon.

shape-outside: polygon(0 0, 0 100px, 100px 200px);
shape-outside: polygon(0 0, 100px 0, 0 50px, 100px 100px, 0 100px);

Effect indication:
Polygon schematic

Polygon effect schematic

//zxx: Firefox browser has a built-in shape editor, you can generate the polygon()coordinate code we need by clicking on the polygon visualization in the Inspector .


Review summary

All the shape functions mentioned above have demos to experience, you can click here: CSS shape-outside basic shape test demo

The red graphics are just for convenience to let everyone know what the shape looks like. In actual development, you can simply omit it or replace it with other characters or bitmaps, such as photos, landscapes, illustrations, etc.

Screenshot of character wrapping typesetting

3. Image

For the image category, only URL and gradient examples are given, because these two types are the most commonly used.

URL irregular graphics

It is known that there is a PNG graphic of a national second-level protected animal parrot, as follows:

Parrot photos

The following CSS code can achieve the text surrounding the parrot outline layout effect:

.shape {
    float: left;
    width: 200px; height: 300px;
    /* text around this parrot*/
    shape-outside: url(./birds.png);
    /* Color and display the parrot*/
    background-color: #cd0000;
    -webkit-mask: url(./birds.png) no-repeat;
    mask: url(./birds.png) no-repeat;
}

The effect achieved is shown in the screenshot below:

Text surround parrot display effect

There is a dedicated demo page for this effect, you can click here: CSS shape-outside PNG image surround demo

Note:url() The size of the linked picture cannot be modified; the url()linked picture cannot be cross-domain, otherwise it will have no effect, because it is not compatible with CORS, open the browser console, you will see an error report similar to the following picture:

Cross domain error

At this time, you need to configure the'Access-Control-Allow-Origin' header to include the domain name of the current page on the server side or CDN.

gradient and surround

The gradient here can be a linear gradient or a radial gradient , as well as a repeat gradient.

For example, to draw a diagonal linear gradient, the CSS is as follows:

.shape {
    float: left;
    width: 150px; height: 120px;
    --gradient: linear-gradient(to right bottom, #cd0000, transparent 50%, transparent 90%, #cd0000);
    shape-outside: var(--gradient);
    background: var(--gradient);
}

The result is shown below:

Gradient and shape surround demo screenshot

There is a CSS property name in the Shape layout shape-image-threshold, which can specify the border transparency value of the text surrounding the image. This will be introduced later.

Three, understand shape-margin

shape-marginIt's easy to understand, that is, when the text surrounds the graphics, the position from the border is very useful. Because in the Shape layout, text wrapping sometimes ignores marginattributes. If you want to open up the spacing, you usually have to use shape-marginattributes.

Usage indication:

/* Length value*/
shape-margin: 10px;
shape-margin: 20mm;

/* Percentage value*/
shape-margin: 60%;

Although this property is included margin, marginthere is a big difference between the behavior and the CSS property. First, shape-marginonly 1 value is supported, marginthen 1~4; then shape-margin, the valid value range is limited, from 0 to the boundary of the floating element (the layout effect is now like a normal floating layout).

Take the case of a little parrot, shape-marginthe performance of different values ​​is shown in the following gif animation:

Surround performance gif screen recording with different values ​​of shape-margin

It can be seen that when shape-marginthe value exceeds a certain amount (exceeding the boundary of the floating element's box), at this time, no change shape-margincan be seen, that is, only the irregular surrounding spacing can be controlled.

You can click here: CSS shape-margin test demo

Fourth, understand shape-image-threshold

The word threshold means "threshold (yu) value", which shape-image-thresholdrefers to the translucent threshold when the image is surrounded. The default is 0.0, that is 0, the boundary of the region where the image transparency is to surround. In the same way, if the value 0.5indicates that the area with transparency less than 0.5 can be surrounded by text.

This attribute is also very practical and easy to understand. For example, if we write an oblique linear gradient from solid color to transparent, the transparency from 0 to 1 is covered. At this time, different shape-image-thresholdvalues ​​will produce different layout changes. The following GIF diagram shows:

Text wrapping performance with different transparency thresholds

The surrounding performance of the following thresholds are respectively shown:

shape-image-threshold: 0.0;
shape-image-threshold: 0.3;
shape-image-threshold: 0.6;
shape-image-threshold: 0.8;

Seeing is believing, you can click here fiercely: CSS different shape-image-threshold value test demo

5. Case: iPhone X Liu Haitou

To achieve the effect of surrounding the iPhone X bangs:

Surrounding list effect implemented by shape-outside url

This is the layout implementation introduced by my iPhone X 2 years ago. It uses CSS Shapes layout. For detailed implementation, please refer to this article: " Using CSS Shapes to implement element scrolling around the bangs of iPhone X ".

I won't go into details here.

Six, conclusion

At this point, the introduction of CSS3 layouts are all completed, namely Flex layout, Grid layout, Columns layout, and Shapes layout of this article. As for CSS Regions layout, depending on the trend, the browser should give up support, so ignore it and do not introduce it. .

Although this article has some length, it is much easier to learn than Grid layout.

Thanks for reading and welcome to communicate!

Guess you like

Origin blog.csdn.net/lu92649264/article/details/112799541