CSS를 사용하다 보면 가끔 쉬운 방법이 있지만 몰라서 어렵게 사용하는 경우가 있는것 같다.
이러한 부분들을 좀 더 쉽게 트릭(?)을 써서 해결하는 방법을 알아보자.
1.여러 요소 중 일부 요소에만 Margin, Padding을 설정하는 경우
여러 요소 중 일부에만 margin, padding을 설정하기 위해 일반적으로 사용하는 방법은먼저 전체 요소에 설정한 후 제외 요소만 별도로 초기값으로 설정 하는것이다.
틀린 방법은 아니지만 선택자 (
nth-child / nth-of-type
) , 의사클래스 (:not()
), 인접 형제 결합자(+
)를 활용하면 간결하게 한 줄로 표현할 수 도 있다.좋지 않은 방법
.item {
margin-right: 4px;
}
.item:lat-child {
margin-rigth: 0;
}
좋은 방법
.item:nth-child(n+2) {
margin-left: 4px;
}
또는
.item + .item {
margin-left: 4px;
}
2. position:absolute 또는 position:fixed와 display:block을 설정하는 경우
position:absolute
, position:fixed
를 설정할 때, display:block
은 자동으로 설정되기 때문에 별도로 설정하지 않아도 되는걸 아시나요?또한,
inline-*
값을 사용할 때, inline
, inline-block
은 block
으로, inline-flex
-> flex
, inline-grid
-> grid
, inline-table
-> table
등으로 변경해서 사용해도 됩니다.그리고
position:absolute
, position:fixed
를 사용할 때, display
값을 설정해야하는 경우는 flex
와 grid
를 지정할 때 뿐입니다.좋지않은 방법
.button:before {
content: "";
position: absolute;
display: block;
}
또는
content: "";
position: fixed;
display: block;
좋은 방법
.button:before {
content: "";
position: absolute;
}
또는
.button:before {
content: "";
position: fixed;
}
3. transform:translate(-50%, -50%)로 가운데 정렬
이 방법은 많은 트러블을 발생시키기로 유명한 방법입니다.
하나의 예로,
position: absolute
와 transform
을 함께 설정하면 크로미움 기반의 브라우저에서 글자가 흐릿해지는 문제가 있습니다.그러나 지금 설명드릴
flexbox
속성을 사용하면, 이러한 문제가 발생하지 않습니다.그리고
position:absolute
와 transform
을 이용해 가운데 정렬을 하는 방법은 flexbox
속성에 비해 더 많은 코드를 추가해야하므로 좋은 방법이 아닙니다.좋지않은 방법
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
좋은 방법
.parent {
display: flex;
}
.child {
margin: auto;
}
4. 블럭요소에 width: 100% 를 사용.
flexbox를 사용해 화면의 크기에 따라 요소를 한줄에 여러개에서 한줄에 하나로 표현주기 위해
요소에
width: 100%
를 설정하게 된다.그러나 한줄에 하나의 요소만 표현하기 위해서는 flex 속성만 설정해주면 별도로
width: 100%
을 설정하지 않아도 된다.좋지 않은 방법
<style>
.parent {
display: flex;
flex-wrap: wrap;
}
.child {
width: 100%;
}
@media (min-width: 1024px) {
.child {
width: 25%;
}
}
</style><div class="parent">
<div class="child">Item 1</div>
<div class="child">Item 2</div>
<div class="child">Item 3</div>
<div class="child">Item 4</div>
</div>
좋은 방법
<style>
@media (min-width: 1024px) {
.parent {
display: flex;
flex-wrap: wrap;
}
.child {
width: 25%;
}
}
</style><div class="parent">
<div class="child">Item 1</div>
<div class="child">Item 2</div>
<div class="child">Item 3</div>
<div class="child">Item 4</div>
</div>
5. Flex 요소에 display:block을 설정
flexbox를 사용할 때, 꼭 기억해야할 점은 flex container를 만들면(
display: flex
), 모든 자식 요소(flex
항목)들은 blockfield 된다.이 말은 요소들의
display
속성 값은 block 요소인 값만 설정될 수 있다는 것이다.즉, inline
inline-block
-> block
, inline-flex
-> flex
inline-grid
-> grid
, inline-table
-> table
으로 설정된다는 것이다.그래서
display: block
는 flex
항목에 설정할 필요가 없다.권장하지 않는 방법
.parent {
display: flex;
}
.child {
display: block;
}
권장하는 방법
.parent {
display: flex;
}
이상으로 CSS를 설정 시 잘못된 사용방법과 권장하는 방법에 대해 알아보았습니다.
효율적인 코드를 작성하시는데 도움이 되시길 바랍니다.
감사합니다.