Heim > Web-Frontend > CSS-Tutorial > Hauptteil

Verlassen Sie sich auf den CSS-Clippfad, um coole Formen im DOM ohne Bilder zu erstellen

WBOY
Freigeben: 2024-07-16 15:02:58
Original
1025 Leute haben es durchsucht

Lean on CSS Clip Path to Make Cool Shapes in the DOM without Images

Einführung

Wenn Sie bis vor ein paar Jahren Hintergrundformen oder Abschnitte einer Website wollten, die alles andere als Rechtecke waren, brauchten Sie höchstwahrscheinlich einen Designer, der Ihnen ein statisches PNG- oder JPEG-Bild zur Verfügung stellte, das nach Bedarf hinzugefügt wurde, aber CSS schon Ich habe seitdem einen langen Weg zurückgelegt, meine Freunde.

Als ich an einem Website-Update arbeitete, das den Inhalt der Seite in verschiedenfarbige Hintergrundabschnitte aufteilte, die zwischen reinem Weiß und sanften Grautönen wechselten, hatte ich in das Designmodell einen Abschnitt eingefügt, dessen Unterkante nach oben und unten geneigt war rechts, anstatt in einem perfekten 90-Grad-Winkel über die Seite zu gehen, wie es bei einem typischen Blockelement der Fall ist.

Jetzt hätte ich den Designer bitten können, ein Hintergrundbild zu erstellen, um dies für mich zu tun, aber stattdessen wollte ich sehen, ob ich es mit der Leistungsfähigkeit von CSS selbst schaffen könnte. Und siehe da, mit CSS Clip-Path könnte ich es schaffen.

Interessante Formen und Grafiken im DOM sind nicht mehr nur die Domäne von Designern. Mit Tools wie CSS-Clip-Path haben Entwickler die Möglichkeit, Elemente umzuformen, und ich zeige Ihnen, wie.


CSS-Clip-Pfad

Wenn Sie wie ich mit der Eigenschaft CSS-Clip-Pfad weniger vertraut sind, erstellt sie einen Ausschneidebereich, der festlegt, welche Teile eines Elements angezeigt werden sollen. Teile, die innerhalb der Region liegen, werden angezeigt, während Teile außerhalb ausgeblendet werden.

Lean on CSS Clip Path to Make Cool Shapes in the DOM without Images

Eine Demo aus den MDN-Clip-Pfad-Dokumenten. Verschiedene Clip-Pfad-Optionen bieten unterschiedliche Ansichten des Heißluftballons und des Textes.

Die Clip-Pfad-Eigenschaft kann eine Vielzahl von Werten annehmen:

  • , das Werte wie die URL für ein SVG-Element mit definiertem Beschneidungspfad akzeptiert.
  • , das Werte wie margin-box und border-box akzeptiert.
  • , das Werte wie Circle() und Rect() akzeptiert.
  • globale Werte, die Werte wie inherit und revert akzeptieren.

Die und Werte können sogar in einem Clip-Pfad kombiniert werden.

/* this CSS combines two different clip path properties */
clip-path: padding-box circle(50px at 0 100px);
Nach dem Login kopieren

In diesem Beitrag wird nicht ausführlich auf alle Eigenschaften eingegangen, die Clip-Path akzeptieren kann, und darauf, wie sie kombiniert werden können, um recht komplexe Formen zu erstellen. Wenn Sie weitere Informationen und Beispiele zu clip=path in Aktion wünschen, empfehle ich, mit der Mozilla-Dokumentation zu beginnen.

Eines der Eigenschaften, die Clip-Pfad akzeptiert, sind polygon(), und das war letztendlich die Lösung, die ich für meinen geneigten Hintergrundabschnitt brauchte.

Das Polygon, das ich mit CSS neu erstellen musste

Lean on CSS Clip Path to Make Cool Shapes in the DOM without Images

Der graue Polygonhintergrund, den ich mit CSS erstellen musste.

Das Bild oben ist ein Screenshot des Abschnitts mit grauem Hintergrund, den ich mit der Eigenschaft polygon() des CSS-Clip-Paths neu erstellen musste. Und als Erstes musste ich einige HTML-Elemente erstellen, auf die ich das CSS anwenden konnte.

polygon() Clip-Pfad vs. rect() Clip-Pfad

Sie fragen sich vielleicht, warum ich mich für die Verwendung der Eigenschaft „polygon()“ anstelle der Eigenschaft „rect()“ mit Clip-Pfad entschieden habe. Während die beiden ähnlich sind, kann polygon() komplexere Polygonformen erstellen und bietet eine größere Vielseitigkeit für fortgeschrittene Designs, indem es Koordinatenpaare akzeptiert, um jeden Scheitelpunkt des Polygons zu definieren, während rect() nur rechteckige Formen verarbeiten kann.

Richten Sie HTML und CSS ein

Die Site, an der ich gearbeitet habe, basierte auf dem statischen Site-Generator Hugo, einem Go-basierten Framework. Hugo verwendet Vorlagen, um den HTML-Code der Website darzustellen. Daher dürfte Ihnen der folgende Beispielcode relativ bekannt vorkommen, wenn Sie sich mit HTML auskennen.

Ein Hinweis zu Vorlagen:

Wenn Sie jemals JSX-Komponenten, Node.js mit Pug oder Handlers oder Jekyll verwendet haben – Hugos Vorlagen sind ähnlich: HTML-Elemente mit Go-Variablen und Funktionen, eingestreut mit {{ }}, um überall in den Vorlagen die richtigen Informationen darzustellen werden injiziert.

Hier ist der Code für den „Rätselabschnitt“ der Seite, den ich wegen des Puzzleteils im Vordergrund dieses Abschnitts genannt habe. Aus Gründen der Klarheit dieses Artikels habe ich die in die Vorlage eingefügten Go-Variablen durch den generierten HTML-Code ersetzt.

single.html

  <div class="about-body">
    <!-- more HTML elements up here -->

    <section class="puzzle-section section">
      <div class="container">
        <div class="row">
          <div class="col-12 col-md-6 col-lg-6">
              <h4 class="mb-3">
                Lorem ipsum dolor
              </h4>
              <p class="mb-5">
                Sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Ipsum dolor sit amet consectetur adipiscing elit pellentesque.
              </p>
              <h4 class="mb-3">
                Duis aute irure dolor in reprehenderit
              </h4>
              <p class="mb-5">
                in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Consectetur adipiscing elit pellentesque habitant morbi tristique senectus et.
              </p>
          </div>
          <div
            class="col-sm-8 offset-sm-2 col-md-6 offset-md-0 col-lg-6 offset-lg-0"
          >
            <img
              class="img-fluid"
              src="/images/about/puzzle-pieces.png"
              alt="Puzzle pieces"
            />
          </div>
        </div>
      </div>
    </section>

     <!-- more HTML elements below -->
  </div>
Nach dem Login kopieren

This section of code is relatively compact, but it deserves discussion. In addition to the HTML elements, there are quite a few CSS classes which come from the Bootstrap library, one of the original open source CSS frameworks for responsive web designs.

Among the custom classes like about-body, which I used for adding custom styling, there are classes like container, row, col-12 or col-md-6, mb-5, and mb-3.

All of the latter classes are Bootstrap classes, which serve to make the text and image elements onscreen share the width of the page when the viewport is over a certain width (col-md-6), or apply a margin-bottom of a certain amount to the

tags (mb-3 or mb-5).

The Bootstrap classes are beside the point for this post though, the class to focus on is the puzzle-section which wraps all the text and puzzle piece image.

This puzzle-section class is where we're going to add the clip-path property to display the light grey background behind the text and image with the slightly tilted, up-and-to-the-right design.

Add the CSS clip-path to shape puzzle-section

As I wasn't quite sure how to style a normal, rectangular

into an uneven shape, I started looking for a solution online and found this helpful, interactive clip-path-focused site, CSS clip-path maker.

Lean on CSS Clip Path to Make Cool Shapes in the DOM without Images

This CSS clip-path maker website is fantastic because it has a whole slew of preset shapes, adjustable image sizes and backgrounds, and the currently displayed image's vertices can be dragged into any arrangement you want. The line at the bottom of the screen shows the exact clip-path CSS values that you can copy/paste into your own project's CSS.

I chose the parallelogram preset shape as my starting point, and then dragged the corners to match the angle of the background section I was trying to recreate from scratch. Once I was satisfied it looked accurate, I copied the CSS line at the bottom of the page to my clipboard.

In my project's SCSS file, I added the copied clip-path CSS in addition to the light grey background-color property and some padding to give the text and puzzle piece images some breathing room on the page.

NOTE: Even though this file shown in the example code is SCSS instead of pure CSS, for this post it shouldn't make a difference here. It should be a direct 1:1 comparison.

about.scss

.about-body {
  // this white sets the white background color for the whole webpage
  background-color: white; 

  .puzzle-section {
    // clip-path code copied from the clip-path maker website
    clip-path: polygon(0 0, 100% 0%, 100% 75%, 0% 100%);
    background-color: light-grey;
    padding: 2rem 0 10rem 0;
  }
}
Nach dem Login kopieren

That little bit of CSS for clip-path was all that was needed to take my perfectly rectangular DOM element and turn it into an imperfect polygon instead. Not too shabby!


Conclusion

CSS is pushing the boundaries of what web developers can do without resorting to images, videos, and custom designed elements all the time. And the satisfaction of figuring out how to do a cool little bit of design on all on your own feels pretty empowering.

A recent example of this was using the CSS clip-path property to create a background box for some text and images that had an uneven bottom edge. With the help of an interactive website dedicated decoding to clip-paths of all shapes and sizes, I was able to make quick work of this slightly skewed polygon.

And let me take a moment to shout out how much I appreciate the folks putting out those little sites or code snippets that solve a very specific problem for another developer - you folks continue to make the Internet a better place.

Check back in a few weeks — I’ll be writing more about JavaScript, React, IoT, or something else related to web development.

If you’d like to make sure you never miss an article I write, sign up for my newsletter here: https://paigeniedringhaus.substack.com

Thanks for reading. I hope learning to reshape how elements look in the DOM with just the power of CSS helps you as much as it's helped me.


Further References & Resources

  • MDN docs, CSS clip-path
  • CSS clip-path generator website

Das obige ist der detaillierte Inhalt vonVerlassen Sie sich auf den CSS-Clippfad, um coole Formen im DOM ohne Bilder zu erstellen. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!