Bersandar pada Laluan Klip CSS untuk Membuat Bentuk Hebat dalam DOM tanpa Imej

WBOY
Lepaskan: 2024-07-16 15:02:58
asal
1025 orang telah melayarinya

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

pengenalan

Sehingga beberapa tahun yang lalu jika anda mahukan bentuk latar belakang atau bahagian tapak web yang selain daripada segi empat tepat, anda berkemungkinan besar memerlukan pereka bentuk untuk memberikan anda imej PNG atau JPEG statik yang akan ditambahkan mengikut keperluan, tetapi CSS mempunyai datang jauh sejak itu, kawan-kawan saya.

Ketika saya sedang mengusahakan kemas kini tapak web yang membahagikan kandungan pada halaman kepada bahagian latar belakang berwarna berbeza, berselang-seli antara warna putih tulen dan kelabu lembut, reka bentuk reka bentuk saya telah menyertakan satu bahagian yang tepi bawahnya condong ke atas dan ke sebelah kanan dan bukannya merentasi halaman pada sudut 90 darjah yang sempurna, seperti yang dilakukan oleh elemen blok biasa.

Sekarang saya boleh meminta pereka bentuk untuk membuat imej latar belakang untuk melakukan ini untuk saya, tetapi sebaliknya saya mahu melihat sama ada saya boleh melakukannya sendiri dengan kuasa CSS. Dan lihatlah, saya boleh, dengan laluan klip CSS.

Bentuk dan visual yang menarik dalam DOM bukan lagi domain pereka bentuk semata-mata, dengan alatan seperti laluan klip CSS, pembangun mempunyai kuasa untuk membentuk semula elemen dan saya akan tunjukkan caranya.


Laluan klip CSS

Jika anda kurang biasa dengan sifat laluan klip CSS, seperti saya, ia mewujudkan kawasan keratan yang menetapkan bahagian elemen mana yang harus ditunjukkan. Bahagian yang berada di dalam kawasan ditunjukkan, manakala bahagian luar disembunyikan.

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

Demo daripada dokumen laluan klip MDN. Pilihan laluan klip yang berbeza memberikan pemandangan belon udara panas dan teks yang berbeza.

Harta clip-path boleh menerima pelbagai jenis nilai:

  • , yang menerima nilai seperti url untuk elemen SVG dengan laluan keratan ditentukan.
  • , yang menerima nilai seperti margin-box dan border-box.
  • , yang menerima nilai seperti circle() dan rect().
  • global-values, yang menerima nilai seperti warisan dan kembalikan.

dan nilai malah boleh digabungkan bersama dalam satu laluan klip.

/* this CSS combines two different clip path properties */
clip-path: padding-box circle(50px at 0 100px);
Salin selepas log masuk

Siaran ini tidak menerangkan secara terperinci tentang semua laluan klip sifat yang boleh diterima dan cara ia boleh digabungkan untuk menghasilkan bentuk yang agak kompleks. Jika anda mahukan lebih banyak maklumat dan contoh clip=path in action, saya syorkan bermula dengan dokumentasi Mozilla.

Salah satu daripada properties clip-path accepts ialah poligon(), dan ini akhirnya menjadi penyelesaian yang saya perlukan untuk bahagian latar belakang condong saya.

Poligon yang saya perlukan untuk mencipta semula dengan CSS

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

Latar belakang poligon kelabu yang saya perlu buat dengan CSS.

Imej di atas ialah tangkapan skrin bahagian latar belakang kelabu yang saya perlu buat semula dengan sifat poligon() laluan klip CSS. Dan perkara pertama yang perlu saya lakukan ialah mencipta beberapa elemen HTML untuk menggunakan CSS.

laluan klip poligon() vs laluan klip rect()

Anda mungkin tertanya-tanya mengapa saya memilih untuk menggunakan sifat poligon() dan bukannya sifat rect() dengan laluan klip. Walaupun kedua-duanya adalah serupa, poligon() boleh mencipta bentuk poligon yang lebih kompleks dan menawarkan fleksibiliti yang lebih besar untuk reka bentuk lanjutan dengan menerima pasangan koordinat untuk mentakrifkan setiap bucu poligon, manakala rect() hanya boleh mengendalikan bentuk segi empat tepat.

Sediakan HTML dan CSS

Tapak yang saya usahakan bergantung pada penjana tapak statik Hugo, rangka kerja berasaskan Go. Hugo menggunakan templat untuk memaparkan HTML tapak, jadi contoh kod di bawah sepatutnya kelihatan agak biasa kepada anda jika anda tahu HTML.

Nota tentang templat:

Jika anda pernah menggunakan komponen JSX, Node.js dengan Pug atau Handlebars atau Jekyll - templat Hugo adalah serupa: Elemen HTML dengan pembolehubah Go dan fungsi yang ditaburkan dengan {{ }} untuk memberikan maklumat yang betul di mana-mana templat disuntik.

Berikut ialah kod untuk apa yang saya namakan sebagai "bahagian teka-teki" halaman kerana kepingan teka-teki di latar depan bahagian ini. Untuk tujuan dan kejelasan artikel ini, saya telah menggantikan pembolehubah Go yang disuntik ke dalam templat dengan HTML yang dijana.

bujang.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>
Salin selepas log masuk

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;
  }
}
Salin selepas log masuk

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

Atas ialah kandungan terperinci Bersandar pada Laluan Klip CSS untuk Membuat Bentuk Hebat dalam DOM tanpa Imej. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!