CSS 클립 경로를 활용하여 이미지 없이 DOM에서 멋진 모양 만들기

WBOY
풀어 주다: 2024-07-16 15:02:58
원래의
1025명이 탐색했습니다.

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

소개

몇 년 전까지만 해도 배경 모양이나 직사각형 이외의 웹 사이트 섹션을 원할 경우 필요에 따라 추가할 정적 PNG 또는 JPEG 이미지를 제공하는 디자이너가 필요했을 가능성이 높았지만 CSS는 그 이후로 먼 길을 왔습니다, 친구들.

페이지 내용을 순백색과 부드러운 회색을 번갈아 가며 다양한 색상의 배경 섹션으로 나누는 웹사이트 업데이트 작업을 할 때 디자인 모형에는 아래쪽 가장자리가 위로 기울어진 섹션 하나가 포함되어 있었습니다. 일반적인 블록 요소처럼 페이지를 완벽한 90도 각도로 가로지르는 대신 오른쪽으로 이동하세요.

이제 디자이너에게 배경 이미지를 만들어 달라고 요청할 수도 있었지만 대신 CSS의 힘으로 직접 할 수 있는지 확인하고 싶었습니다. 그리고 CSS 클립 경로를 사용하면 가능합니다.

DOM의 흥미로운 모양과 시각적 요소는 더 이상 순전히 디자이너의 영역이 아닙니다. CSS 클립 경로와 같은 도구를 사용하면 개발자는 요소의 모양을 변경할 수 있으며 그 방법을 알려 드리겠습니다.


CSS 클립 경로

저처럼 CSS 클립 경로 속성에 익숙하지 않다면 요소의 어느 부분을 표시할지 설정하는 클리핑 영역을 생성합니다. 영역 내부에 있는 부분은 표시되고, 영역 외부에 있는 부분은 숨겨집니다.

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

MDN 클립 경로 문서의 데모입니다. 다양한 클립 경로 옵션은 열기구와 텍스트의 다양한 보기를 제공합니다.

clip-path 속성은 매우 다양한 값을 허용할 수 있습니다.

  • 클리핑 경로가 정의된 SVG 요소에 대해 url과 같은 값을 허용하는
  • margin-box 및 border-box와 같은 값을 허용하는
  • , Circle() 및 ect()와 같은 값을 허용합니다.
  • 상속 및 되돌리기와 같은 값을 허용하는 전역 값.

<기하학 상자> 및 <기본 모양> 값을 하나의 클립 경로로 결합할 수도 있습니다.

/* this CSS combines two different clip path properties */
clip-path: padding-box circle(50px at 0 100px);
로그인 후 복사

이 게시물에서는 클립 경로가 허용할 수 있는 모든 속성과 이러한 속성을 결합하여 매우 복잡한 모양을 만드는 방법에 대해 자세히 설명하지 않습니다. Clip=path에 대한 자세한 정보와 예를 보려면 Mozilla 문서부터 시작하는 것이 좋습니다.

<기본 모양> 클립 경로에서 허용하는 속성은 polygon()이며 이는 기울어진 배경 섹션에 필요한 솔루션이 되었습니다.

CSS로 다시 만드는 데 필요한 다각형

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

CSS로 만들어야 했던 회색 폴리곤 배경

위 이미지는 CSS 클립 경로의 폴리곤() 속성을 사용하여 다시 생성해야 했던 회색 배경 섹션의 스크린샷입니다. 그리고 가장 먼저 해야 할 일은 CSS를 적용할 HTML 요소를 만드는 것이었습니다.

폴리곤() 클립 경로 대 ect() 클립 경로

clip-path에 ret() 속성 대신에 Polygon() 속성을 사용하기로 선택한 이유가 궁금하실 것입니다. 두 가지가 비슷하지만 폴리곤()은 더 복잡한 다각형 모양을 만들 수 있고 좌표 쌍을 사용하여 다각형의 각 꼭지점을 정의하는 방식으로 고급 디자인에 더 큰 다양성을 제공하는 반면, ect()는 직사각형 모양만 처리할 수 있습니다.

HTML 및 CSS 설정

제가 작업하던 사이트는 Go 기반 프레임워크인 정적 사이트 생성기 Hugo를 사용했습니다. Hugo는 템플릿을 사용하여 사이트의 HTML을 렌더링하므로 HTML을 알고 있는 경우 아래 예제 코드가 비교적 친숙해 보일 것입니다.

템플릿 관련 참고 사항:

JSX 구성 요소, Pug 또는 Handlebars가 포함된 Node.js 또는 Jekyll을 사용한 적이 있다면 Hugo의 템플릿은 유사합니다. 템플릿이 어디에 있든 올바른 정보를 렌더링하기 위해 {{ }}가 뿌려진 Go 변수와 함수가 포함된 HTML 요소입니다. 주입됩니다.

다음은 이 섹션의 전경에 있는 퍼즐 조각으로 인해 페이지의 '퍼즐 섹션'이라는 별명을 붙인 코드입니다. 이 기사의 목적과 명확성을 위해 템플릿에 삽입된 Go 변수를 생성된 HTML로 대체했습니다.

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>
로그인 후 복사

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;
  }
}
로그인 후 복사

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

위 내용은 CSS 클립 경로를 활용하여 이미지 없이 DOM에서 멋진 모양 만들기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!