내 CSS 파일의 내용을 어떻게 구성해야합니까?
이 질문은 .css 파일 내에서 실제 CSS 지시문 자체를 구성하는 것에 관한 것입니다. 새 페이지 또는 페이지 집합을 개발할 때 일반적으로 .css 파일에 직접 지시문을 추가하고 가능한 한 리팩터링을 시도합니다. 시간이 지나면 수백 (또는 수천) 줄의 줄이 생기고 레이아웃을 조정할 때 필요한 것을 찾기가 어려울 수 있습니다.
누구든지 지침을 구성하는 방법에 대한 조언이 있습니까?
- DOM을 모방하여 하향식으로 구성해야합니까?
- UI의 동일한 부분을 지원하는 요소에 대한 지시문을 함께 배치하여 기능적으로 구성해야합니까?
- 선택기를 기준으로 모든 것을 알파벳순으로 정렬해야합니까?
- 이러한 접근 방식의 조합?
또한 하나의 파일에 CSS를 얼마나 보관해야하는지에 제한이 있습니까? 별도의 파일로 나누는 것이 좋은 생각 일 수 있습니까? 1000 줄? 아니면 모든 것을 한 곳에 보관하는 것이 항상 좋은 생각입니까?
관련 질문 : CSS 규칙을 구성하는 가장 좋은 방법은 무엇입니까?
시작하려면 다음 세 가지 슬라이드 공유 프레젠테이션을 살펴보십시오.
첫째, 가장 중요한 것은 CSS를 문서화하는 것입니다. CSS를 구성하는 데 사용하는 방법이 무엇이든 일관성을 유지하고 문서화하십시오. 각 파일의 맨 위에 해당 파일의 내용을 설명하고, 아마도 목차를 제공하고, 고유 한 태그를 쉽게 검색 할 수 있으므로 편집기에서 해당 섹션으로 쉽게 이동할 수 있습니다.
CSS를 여러 파일로 분할하려면 반드시 그렇게하십시오. Oli는 추가 HTTP 요청이 비쌀 수 있지만 두 가지 장점을 모두 활용할 수 있다고 이미 언급했습니다. 일종의 빌드 스크립트를 사용하여 잘 문서화 된 모듈 식 CSS를 압축 된 단일 CSS 파일에 게시합니다. YUI 압축기는 압축에 도움이 될 수 있습니다.
지금까지 다른 사람들이 말한 것과 달리 각 속성을 별도의 줄에 작성하고 들여 쓰기를 사용하여 관련 규칙을 그룹화하는 것을 선호합니다. 예를 들어 Oli의 예를 따릅니다.
#content {
/* css */
}
#content div {
/* css */
}
#content span {
/* css */
}
#content etc {
/* css */
}
#header {
/* css */
}
#header etc {
/* css */
}
따라서 파일 구조를 쉽게 따를 수 있으며, 특히 그룹간에 충분한 공백과 명확하게 표시된 주석 (빠르게 훑어보기는 쉽지 않음)과 편집하기 쉽습니다 (단일 긴 CSS 줄을 훑어 볼 필요가 없기 때문). 각 규칙에 대해).
캐스케이드 와 특이성을 이해하고 사용하십시오 (따라서 선택기를 알파벳순으로 정렬하는 것이 적절합니다).
내 CSS를 여러 파일로 분할할지 여부와 어떤 파일에서 사이트와 CSS의 크기와 복잡성에 따라 달라집니다. 나는 항상 최소한 reset.css
. 사이트 탐색 메뉴가 약간 복잡해지고 양식 스타일 을 지정할 수있는 CSS가 많이 있는 경우 layout.css
일반적인 페이지 레이아웃 이 수반되는 경향이 있습니다 . 그 외에는 아직 스스로 알아 내고 있습니다. 내가 가질 수 와 , 색상 / 그래픽과 타이포그래피 떨어져 분할하는 모든 HTML 태그에 대한 완전한 기본 스타일을 제공하기 위해 ...nav.css
forms.css
colors.css
type.css/fonts.css
base.css
나는 다음과 같이 내 CSS를 얻는 경향이 있습니다.
- reset.css
- base.css : 페이지의 주요 섹션에 대한 레이아웃을 설정했습니다.
- 일반 스타일
- 헤더
- Nav
- 함유량
- 보행인
- additional- [페이지 이름] .css : 한 페이지에서만 사용되는 클래스
그러나 읽기가 가장 쉽습니다!
진지하게, 당신은 수십억 개의 제안을 받게 될 것이지만 당신은 몇 가지 방법만을 좋아할 것입니다.
그래도 몇 가지 말할 것 :
- CSS 파일을 덩어리로 나누면 머리 속에 정리하는 데 도움이되지만 브라우저에서 더 많은 요청을 받게되므로 궁극적으로 서버 실행 속도가 느려지고 (더 많은 요청) 브라우저가 페이지를 표시하는 데 더 오래 걸립니다. 명심하십시오.
- 임의의 줄 수라는 이유만으로 파일을 분할하는 것은 어리석은 일입니다 (편집기가 끔찍하다는 점을 제외하면-이 경우 새 편집기를 가져옵니다).
개인적으로 CSS를 다음과 같이 코딩합니다.
* { /* css */ }
body { /* css */ }
#wrapper { /* css */ }
#innerwrapper { /* css */ }
#content { /* css */ }
#content div { /* css */ }
#content span { /* css */ }
#content etc { /* css */ }
#header { /* css */ }
#header etc { /* css */ }
#footer { /* css */ }
#footer etc { /* css */ }
.class1 { /* css */ }
.class2 { /* css */ }
.class3 { /* css */ }
.classn { /* css */ }
규칙을 한 줄에 유지하면 파일을 매우 빠르게 훑어보고 어떤 규칙이 있는지 확인할 수 있습니다. 그것들이 확장되면 어떤 규칙이 적용되는지 알아 내려고 노력하는 것과 너무 흡사합니다.
CSS 형식을 지정하는 방법에는 여러 가지가 있습니다. 궁극적으로 가장 편하게 쓰는 것은 당신에게 달려 있지만, 이것은 더 크고 복잡한 프로젝트를 위해 CSS를 관리하는 데 도움이 될 것입니다. 중요하지는 않지만 BEM과 SMACSS의 조합을 사용하는 경향이 있습니다.
BEM (블록, 요소, 수정 자)
BEM은 프런트 엔드 코드를보다 쉽게 읽고 이해하고, 작업하기 쉽고, 확장하기 쉽고, 더 강력하고 명시 적이며 훨씬 더 엄격하게 만드는 매우 유용하고 강력하며 간단한 명명 규칙입니다.
블록
다음과 같이 그 자체로 의미있는 독립형 엔티티 :
header, container, menu, checkbox, input
요소
블록의 일부이며 독립형 의미가 없습니다. 의미 론적으로 블록에 연결되어 있습니다.
menu item, list item, checkbox caption, header title
수정 자
블록 또는 요소에 대한 플래그. 이를 사용하여 모양이나 동작을 변경하십시오.
disabled, highlighted, checked, fixed, size big, color yellow
OOCSS
OOCSS의 목적은 코드 재사용을 장려하고 궁극적으로 추가 및 유지 관리가 더 쉬운 더 빠르고 효율적인 스타일 시트를 장려하는 것입니다.
OOCSS는 두 가지 주요 원칙을 기반으로합니다.
- 피부에서 구조 분리
즉, 반복되는 시각적 기능 (예 : 배경 및 테두리 스타일)을 별도의 "스킨"으로 정의하여 다양한 개체와 혼합하여 많은 코드없이 다양한 시각적 다양성을 얻을 수 있습니다. 모듈 개체 및 해당 스킨을 참조하십시오.
- 용기와 내용물의 분리
본질적으로 이것은 "위치 종속 스타일을 거의 사용하지 않는다"는 의미입니다. 물체는 어디에 두든 동일하게 보여야합니다. 따라서 .myObject h2 {...}로 특정 스타일을 지정하는 대신 .myObject와 같은 문제를 설명하는 클래스를 만들고 적용합니다. 이것은 다음과 같은 보증을 제공합니다. (1) 분류되지 않은 모든는 동일하게 보입니다. (2) 카테고리 클래스 (믹스 인이라고 함)의 모든 요소는 동일하게 보입니다. 3) 실제로 .myObject h2가 정상처럼 보이기를 원하는 경우에 대한 재정의 스타일을 만들 필요가 없습니다.
SMACSS
SMACSS는 디자인 프로세스를 검토하는 방법이며 이러한 엄격한 프레임 워크를 유연한 사고 프로세스에 맞추는 방법입니다. CSS를 사용할 때 사이트 개발에 대한 일관된 접근 방식을 문서화하려는 시도입니다.
SMACSS의 핵심은 분류입니다. CSS 규칙을 분류함으로써 패턴을보기 시작하고 이러한 각 패턴에 대한 더 나은 사례를 정의 할 수 있습니다.
카테고리에는 5 가지 유형이 있습니다.
/* Base */
/* Layout */
/* Modules */
/* State */
/* Theme */
기본 재설정 및 기본 요소 스타일을 포함합니다. 또한 특정 상황에서 나중에 문서에서 덮어 쓸 수있는 단추, 격자 등과 같은 컨트롤에 대한 기본 스타일을 가질 수 있습니다.
레이아웃 모든 탐색, 이동 경로, 사이트 맵 등을 포함합니다.
모듈 은 연락처 양식 스타일, 홈페이지 타일, 제품 목록 등과 같은 영역 별 스타일을 포함합니다.
State isSelected, isActive, hasError, wasSuccessful 등과 같은 상태 클래스를 포함합니다.
테마 테마 와 관련된 모든 스타일을 포함합니다.
There are too many to detail here but have a look at these others as well:
I go with this order:
- General style rules, usually applied to the bare elements (a, ul, ol, etc.) but they could be general classes as well (.button, .error)
- Page layout rules applied to most/all pages
- Individual page layout rules
For any of the style rules that apply to a single page, or a small grouping pages, I will set the body to an id and a class, making it easy to target particular pages. The id is the base name of the file, and the class is the directory name where it is in.
I've tried a bunch of different strategies, and I always come back to this style:
.class {border: 1px solid #000; padding: 0; margin: 0;}
This is the friendliest when it comes to a large amount of declarations.
Mr. Snook wrote about this almost four years ago :).
Factor out common styles. Not styles that just happen to be the same, styles that are intended to be the same - where changing the style for one selector will likely mean you'll want to change the other as well. I put an example of this style in another post: Create a variable in CSS file for use within that CSS file.
Apart from that, group related rules together. And split your rules into multiple files... unless every page actually needs every rule.
As the actual ordering is a vital part of how your CSS is applied, it seems a bit foolish to go ahead with the "alphabetical" suggestion.
In general you want to group items together by the area of the page they affect. E.g. main styles that affect everything go first, then header and footer styles, then navigation styles, then main content styles, then secondary content styles.
I would avoid breaking into multiple files at this point, as it can be more difficult to maintain. (It's very difficult to keep the cascade order in your head when you have six CSS files open). However, I would definitely start moving styles to different files if they only apply to a subset of pages, e.g. form styles only get linked to a page when the page actually contains a form.
CSS files are cached on the client. So it's good practice to keep all of your styles in one file. But when developing, I find it useful to structure my CSS according to domains.
For instance: reset.css
, design.css
, text.css
and so forth. When I release the final product, I mash all the styles into one file.
Another useful tip is to focus readability on the rules, not the styles.
While:
ul li
{
margin-left: 10px;
padding: 0;
}
Looks good, it's not easy finding the the rules when you've got, say, 100 lines of code.
Instead I use this format:
rule { property: value; property: value; }
rule { property: value; property: value; }
I used to worry about this incessantly, but Firebug came to the rescue.
These days, it's much easier to look at how your styles are interrelating through Firebug and figure out from there what needs to be done.
Sure, definitely make sure there's a reasonable structure that groups related styles together, but don't go overboard. Firebug makes things so much easier to track that you don't have to worry about making a perfect css structure up front.
Here is what I do. I have a CSS index page with no directives on it and which calls the different files. Here is a short sample:
@import url("stylesheet-name/complete-reset.css");
@import url("stylesheet-name/colors.css");
@import url("stylesheet-name/structure.css");
@import url("stylesheet-name/html-tags.css");
@import url("stylesheet-name/menu-items.css");
@import url("stylesheet-name/portfolio.css");
@import url("stylesheet-name/error-messages.css");
It starts with a complete reset. The next file defines the color palette for easy reference. Then I style the main <div/>
s that determine the layout, header, footer, number of columns, where they fit, etc... The html tags definses <body/>
, <h1/>
, <p/>
, t etc... Next come the specific sections of the site.
It's very scalabale and very clear. Much more friendly to find code to change and to a dd new sections.
ITCSS
By Harry Roberts (CSS Wizardry)
Defines global namespace and cascade, and helps keep selectors specificity low.
Structure
The first two only apply if you are using a preprocessor.
- (Settings)
- (Tools)
- Generics
- Elements
- Objects
- Components
- Trumps
Normally I do this:
<link rel="stylesheet" href="css/style.css">
In style.css I @import the following:
@import url(colors.css); @import url(grid.css); @import url(custom.css); + some more files (if needed)
In
colors.css
I@import
the following (when using the CSS custom properties):@import url(root/variable.css);
Everything is in order and easy to get any part of code to edit. I'll be glad if it helps somehow.
참고URL : https://stackoverflow.com/questions/146106/how-should-i-organize-the-contents-of-my-css-files
'Development Tip' 카테고리의 다른 글
정확히 PHI 명령어의 기능과 LLVM에서 사용하는 방법 (0) | 2020.10.19 |
---|---|
jq를 사용하여 json 문서의 단일 값을 어떻게 업데이트합니까? (0) | 2020.10.19 |
수업 전 Junit (비 정적) (0) | 2020.10.19 |
빈혈 도메인 모델 피하기-실제 예 (0) | 2020.10.19 |
Razor / CSHTML-우리가 가진 것보다 어떤 이점이 있습니까? (0) | 2020.10.19 |