초보자가 자주 저지르는 SS 실수

WBOY
풀어 주다: 2024-08-26 06:33:31
원래의
752명이 탐색했습니다.

SS Mistakes that Beginners Often Make

CSS는 보기만큼 간단하지 않으며 개발자는 종종 실수를 하여 무엇을 해야 할지 고민하게 됩니다. CSS는 대부분의 개발자가 CSS를 작성하려고 할 때 방해하는 일반적인 실수로 인해 직관적이지 않고 작업하기 어려운 언어로 인식됩니다. 결과적으로 대부분의 개발자는 자체 CSS를 작성하는 것을 피하기 위해 Bootstrap 및 Tailwind CSS와 같은 CSS 프레임워크를 사용하기로 선택합니다.

이 블로그에서는 개발자가 자주 저지르는 5가지 일반적인 실수에 대해 논의하겠습니다. 이러한 실수를 인식하고 피하면 다음과 같은 CSS를 작성하는 데 도움이 됩니다.

  • 노트북뿐만 아니라 다양한 기기에서 작동
  • 처음 사용해도 작동합니다
  • CSS를 사용하면 좌절감을 덜 수 있습니다

자세히 살펴보겠습니다.

실수 1: CSS Reset을 사용하지 않음

이것은 제가 발견한 놀라운 사실 중 하나이며 제가 그동안 CSS를 잘못 사용해 왔다는 사실을 깨달았습니다. 브라우저에는 스타일시트가 없는 경우 대체 역할을 하는 기본 스타일이 있습니다. 그러나 이러한 기본 스타일은 브라우저마다 다릅니다. 어떤 경우든 두 브라우저가 동일한 기본 스타일을 제공하는 경우는 거의 없으므로 스타일이 효과적인지 확인하는 유일한 방법은 CSS 재설정을 사용하는 것입니다.

CSS 재설정은 모든 HTML 요소의 모든 스타일을 예측 가능한 기준 값으로 재설정(또는 설정)하는 것을 의미합니다. 이 기능의 장점은 CSS 재설정을 효과적으로 포함하면 페이지의 모든 요소가 처음부터 동일한 것처럼 스타일을 지정할 수 있다는 것입니다.

CSS 재설정은 다양한 브라우저에서 일관된 스타일을 유지하는 데 도움이 되는 백지 상태입니다. 대부분의 경우 여백:0 및 패딩:0을 설정해야 하지만 다른 요소를 재설정해야 합니다.
샘플 재설정 코드는 다음과 같습니다.

* {
  margin: 0;
  padding: 0;
  border: 0;
  outline: 0;
  font-weight: inherit;
  font-style: inherit;
  font-size: 100%;
  font-family: inherit;
  vertical-align: baseline;
}
/* remember to define focus styles! */
:focus {
  outline: 0;
}
body {
  line-height: 1;
  color: black;
  background: white;
}
ol,
ul {
  list-style: none;
}
/* tables still need 'cellspacing="0"' in the markup */
table {
  border-collapse: separate;
  border-spacing: 0;
}
caption,
th,
td {
  text-align: left;
  font-weight: normal;
}
blockquote::before,
blockquote::after,
q::before,
q::after {
  content: "";
}
blockquote,
q {
  quotes: "" "";
}
로그인 후 복사

실수 2: px 단위 사용

저는 실제로 글꼴 크기, 여백, 패딩, 높이 또는 무게 속성에 px 단위를 사용한 죄도 있습니다. 경우에 따라 px 단위를 사용해도 괜찮을 수 있지만 지나치게 의존하면 접근성 문제가 발생할 수 있습니다.

MDN에 따르면 사용자가 일부 브라우저에서 글꼴 크기를 변경할 수 없기 때문에 글꼴 크기를 px 단위로 정의하는 기능에 액세스할 수 없습니다. 예를 들어, 시력이 제한된 사용자는 웹 디자이너가 선택한 크기보다 훨씬 더 큰 글꼴 크기를 설정하기를 원할 수 있습니다. 포괄적인 디자인을 만들고 싶다면 글꼴 크기에 사용하지 마세요.

그러나 px 단위는 콘텐츠의 높이와 너비를 설정하는 데에도 적합하지 않습니다. 사용자가 브라우저에서 기본 글꼴 크기를 늘리면 콘텐츠가 오버플로될 수도 있기 때문입니다. 미디어 내 쿼리에서 px 단위를 사용하면 사용자가 확대하거나 기본 글꼴 크기를 변경할 때 레이아웃에도 영향을 줍니다. 

? 실수

p {
  font-size: 16px;
 /*this prevents users from resizing the font-size*/
  line-height: 20px;
  margin-bottom: 8px;
}
로그인 후 복사

✅ 맞습니다

body {
  font-size: 16px;
}
p {
  font-size: 1rem;
  line-height: 1.25;
  margin-bottom: 0.5em;
}
로그인 후 복사

실수 3: ID를 선택자로 사용

웹 개발에서 가장 간과되는 문제 중 하나는 너무 구체적이고 재정의하기 어려운 과적격 선택기를 사용하는 것입니다. ID 선택기는 CSS에서 더 구체적입니다. 즉, ID 선택기를 재정의하거나 다른 구성 요소에서 스타일을 재사용할 수 없습니다.

항상 CSS 선택기가 작동하는 데 필요한 최소 수준의 구체성을 사용하여 작성하세요. 추가 보풀을 모두 포함하면 더 안전하고 정확해 보일 수 있지만 CSS 선택기의 경우 구체성은 두 가지 수준, 즉 구체적이고 구체적이지 않습니다.

? 실수

#header {
  font-size: 1em;
  line-height: normal;
}
로그인 후 복사

✅ 맞습니다

.header {
  font-size: 1em;
  line-height: normal;
}
로그인 후 복사

일반적으로 CSS에서는 지나치게 구체적인 선택기를 사용하지 않는 것이 좋습니다. CSS 특정성 토너먼트는 너무 강력한 선택기를 사용하는 것이 왜 좋지 않은지 보여줍니다. 토너먼트에서 셀렉터가 매우 강력하면 조기에 빠르게 승리할 수 있습니다. 즉, 이를 이길 수 있는 유일한 방법은 훨씬 더 강력한 셀렉터를 작성하는 것입니다.

특정성이 항상 확대되는 경향을 특정성 전쟁이라고 합니다. 핵무기 비축과 마찬가지로 이 전쟁에서는 누구도 승리할 수 없습니다. 구체성이 높아질수록 상황을 완화하기가 더 어려워질 뿐입니다. 본격적인 특정성 전쟁을 피하는 가장 좋은 방법은 처음부터 매우 구체적인 선택자를 사용하지 않는 것입니다.

실수-4: 이름이 지정된 색상

조사를 하면서 발견한 또 다른 실수는 색상 이름에 대한 문제입니다. 개발자는 특정 색상으로 인식되는 것이 브라우저에 따라 매우 다르게 보인다는 점을 종종 무시합니다.

말하자면: 색상: 빨간색; 본질적으로 브라우저가 빨간색이라고 생각하는 것을 표시해야 한다고 말하는 것입니다. 모든 브라우저에서 기능이 올바르게 작동하도록 하면서 배운 점이 있다면 웹페이지 표시 방법을 브라우저가 결정하도록 해서는 안 된다는 것입니다.

Instead, you should go to the effort to find the actual hex value for the color you’re trying to use. That way, you can make sure it’s the same color displayed across all browsers. You can use a color cheat sheet that provides a preview and the hex value of a color.

? Mistake

.header {
  font-size: 1em;
  line-height: normal;
  color: red;
}
로그인 후 복사

✅ Correct

.header {
  font-size: 1em;
  line-height: normal;
  color: rgb(255, 0, 0);
}
로그인 후 복사

Mistake 5: Not Using Shorthand Properties

As a developer, one rule is to never repeat yourself. Therefore, you should find ways to minimize the number of lines of code that you write.

One common problem with CSS is understanding shorthand properties for things like margin, padding and inset. As a confession, I also struggle with this problem and often have to look to the documentation on whether margin: 0 5px sets the margin in top-bottom or left-right.

? Mistake

.my-cool-div {
  margin-top: 50px;
  margin-right: 0;
  margin-bottom: 50px;
  margin-left: 0;
  background-image: url(background.png);
  background-repeat: repeat-y;
  background-position: center top;
}
로그인 후 복사

✅ Correct

.my-cool-div {
  margin: 50px 0;
  background: url(background.png) repeat-y center top;
}

로그인 후 복사

Using shorthand CSS improves efficiency and makes it easier to maintain our code. However, this could take time to master and I recommend checking the documentation.

Mistake 6: Overreliance on Position Absolute

Position absolute is that one band-aid solution that can cause more problems as it breaks the document flow. When using positions absolute, MDN recommends that you ensure that elements that are positioned with an absolute or fixed value do not obscure other content when the page is zoomed to increase text size.

Position absolute should be the last choice since it has some effects such as pulling the element out of the flow and making it stack over other things. 

Furthermore, elements positioned absolutely don't naturally adapt to changes in screen size or parent element dimensions, which can break the layout on different devices.

? Mistake

.sidebar {
  position: absolute;
  top: 50px;
  right: 0;
  width: 30%;
  background-color: #e0e0e0;
  padding: 20px;
}
로그인 후 복사

✅ Correct

.sidebar {
  transform: translateY(50px) translateX(0);
  /* Moves the element down by 50px */
  width: 30%;
  background-color: #e0e0e0;
  padding: 20px;
}
로그인 후 복사

In this example, we see that we can achieve the same functionality without breaking the document flow by using transform to move the sidebar down by 50px.

Mistake 7: Collapsing Margins

Collapsing margins can be really hard to understand and frustrating to decode since you might not understand why your applied margin or padding is not working as expected.

The top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the individual margins (or just one of them if they are equal), a behavior known as margin collapsing. Note that the margins of floating and absolutely positioned elements never collapse.

Understanding margin collapse is essential for achieving consistent spacing in your layouts, particularly in scenarios where you want to ensure a specific amount of space between elements.

One solution to collapsing margins is using padding, especially for child elements rather than margins. It is generally advised not to add margin to the child element, especially in JavaScript frameworks such as react since this might affect their reusability.

You must always remember that adding a margin to a child element can affect the position of the parent element as the margins collapse.

? Mistake

/* html */
/* 
<div class="element1">Element 1</div>
<div class="element2">Element 2</div> 
*/
.element1 {
  margin-bottom: 20px;
}
.element2 {
  margin-top: 30px;
}
/* the total margin will be 30px rather than 50px */
로그인 후 복사

✅ Correct

.element1 {
  margin-bottom: 20px;
  padding-bottom: 1px;
  /* Prevents collapse */
}
.element2 {
  margin-top: 30px;
}
로그인 후 복사

Conclusion

I hope you enjoyed this article, and that it gave you a sense of how to avoid the topmost common mistakes developers make when they write CSS. There are many mistakes not covered in this blog such as separating between layout and content elements, overusing flex box and much more. Comment below with some other mistakes.

위 내용은 초보자가 자주 저지르는 SS 실수의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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