A LIST Apart: For People Who Make Websites

블링블링 CSS3

by Chris Mills

친애하는 디자이너 여러분, 우리는 모두 CSS3을 사랑합니다. 핵 같은 걸 쓰지 않고도 끝내주는 사이트를 쉽고 단순하게 만들 수 있는 CSS3 말입니다. CSS3의 그래디언트, 그림자, 둥근 테두리, 애니메이션, 투명도 같은 기능을 이용하면 포토샵에 매달리는 시간과 악몽처럼 중첩되는 <div>를 줄이고, 더 유연하고 재미있게 일할 수 있습니다. 바에서 친구들예게 아이패드에 최근 시도해 본 휘황찬란한 효과를 보여주거나, 술 한잔 기울이면서 자신감에 고조될 시간도 더 늘어나죠. CSS3를 만나 보세요. 우리는 모두 이런 순간을 즐겼습니다.

All you disco-dancing designers out there (no more anticipation of alliteration) have been loving the new features CSS3 provides for making websites look cool in an easier, less hackish, and more straightforward fashion. Features like CSS3 gradients, drop shadows, rounded corners, animations, and opacity are giving us the promise of less time spent in Photoshop, fewer horribly nested <div>s, more flexibility, and more fun! Not to mention more time down at the pub, excitedly showing your friends your latest cool experiments on your iPad, while sipping on a smooth glass of ale with an intense air of self-satisfaction and smugness. Face it, most of us have enjoyed such a moment!

나같이 자타가 공인하는 디자인 아마추어도 CSS3를 통해 멋진 디자인을 만들 수 있습니다. CSS3는 당장 쓸 수 있고, 재미있고, 웹의 모양을 진화시킬 수 있습니다. ..최소한 이론적으로는 그렇습니다. 현실은 조금 다르지만요.

The new breed of CSS3 shizzle even allows a self-confessed design amateur like myself to produce some fairly tasty looking designs. CSS3 is here, CSS3 is fun, and CSS3 allows us to evolve the look of the web as we go. At least, that's the theory. But the reality is a bit different:

좋아요. 아마 다들 아는 얘기죠. 흥미로운 실험은 잠시 옆으로 제껴두고, 인터넷 익스플로러 6가 정말로 역사의 뒤켠으로 사라지고 CSS4에 대해 배울 때까지 기다리지 않아도 정말로 쓸 수 있는 CSS3 기능엔 뭐가 있을까요?

Ok, I'm probably not saying anything that you don't know already. But putting our fun experiments aside, what CSS3 stuff can we reallystart using in a wide variety of production sites, right now, without having to wait 10 years until IE6 finally dies of old age and we have to start learning CSS4?

CSS3의 기능을 전부 다룰 생각은 없습니다. 그렇게 하려면 아마 크리스마스까지 계속 글을 써야겠죠. 이 글에서는 현실로 내려와서 우리 모두 알고 있는 기본 기능을 살펴보고, 가능한 한 많은 브라우저에서 동작하도록 해 보겠습니다.

I won't cover anything approaching allof the features found in CSS3, as, well, I'd be here until Christmas and miss Coronation Street. For now, I will get down to business and look at some of the basic CSS3 yumminess we all know and love, and how to make it as cross-browser as possible:

적당한 예제?

요점을 묘사할만한 조그맣고 블링블링한 박스를 하나 만들었습니다. 오페라, 파이어폭스, 크롬 최근 버전에서는 이렇게 보입니다.

To illustrate my points, I'm going to create a funky little bling box and use it as my playground. Here's what it looks like in the latest versions of Opera, Firefox, Chrome, and Safari:

그림 1. CSS3를 완전히 지원하는 브라우저에서 본 CSS3 예제

Fig. 1: CSS3 example as shown in a browser that fully supports CSS3.

진행하면서 이 예제를 계속 수정하겠습니다. 이 예제를 브라우저에서 보고 원하는대로 수정하세요. 제가 만든 것보다는 훨씬 낫겠죠.

We will make some updates as we go along. You can view the initial bling example running live: feel free to do some testing and updates of your own, as I'm sure you can get it looking tastier than I can.

HTML5의 <section>에 내용을 넣고 CSS로 장식했습니다. 코드 전체를 해설하면 따분할테니 생략하고, 몇 가지 흥미로운 부분만 설명하겠습니다.

In this example, I've taken a simple HTML5 page with a <section> element containing some content, and blinged up that <section>with some fairly gratuitous CSS. I'll not walk you through all the code, as you would find that tedious; I will, however, point out a few of the more interesting features.

웹 폰트

Font Squirrel에서 멋진 서체를 찾았고 @font-face 생성기를 써서 크로스 브라우저 코드를 만들었습니다.

To start with, I went to Font Squirrel, found a fairly nice looking font, and then used the @font-face generatorto create cross-browser code for including my font which will work across pretty much any browser:

@font-face {
  font-family: 'MEgalopolisExtraRegular';
  src: url('megalopolisextra-webfont.eot');
  src: url('megalopolisextra-webfont.eot?#iefix')
    format('embedded-opentype'),
  url('megalopolisextra-webfont.woff') format('woff'),
  url('megalopolisextra-webfont.ttf') format('truetype'),
  url('megalopolisextra-webfont.svg#MEgalopolisExtraRegular')
    format('svg');
  font-weight: normal;
  font-style: normal;
}

둥근 테두리

테두리를 둥글게 만들어서 예제를 좀 더 웹 2.0 처럼 보이게 했습니다.

To make my example Web 2.0 compliant, I made sure to give my box at least one rounded corner:

border-radius: 30px 0 0 0;

텍스트 그림자

h1 요소에 그림자를 넣어서 입체감을 표현했습니다.

Next, I included several text shadows on the h1to give it a rather nice-looking 3D effect:

text-shadow: 0 0 1px #000,
  0 0 1px #aaa,
  0 0 2px #999,
  0 0 3px #888,
  0 0 4px #666,
  0 3px 3px rgba(0,0,0,0.5),
  0 4px 10px rgba(0,0,0,0.5);

문단에도 그림자를 약간 넣어서 배경색에 어두운 색을 선택했을때도 읽기 쉽게 만들었습니다.

I also included a simple text shadow on the paragraph to ensure readability if darker colors are chosen for the background color:

text-shadow: 1px 1px 1px #bbb;

(텍스트 그림자는 내 예제보다 훨씬 나은 Jan Henrik Helmers의 예제를 보고 영감을 얻었습니다)

(Note: inspiration for my text shadow effect was taken from the rather masterful Jan Henrik Helmers.)

그림자

바깥쪽 박스에는 그림자를 여러 개 넣어서 광원이 여러 개 있는 것처럼 좀 더 자연스럽게 보이게 했고 안쪽 박스는 입체감있게 표현했습니다(inset)

I also added multiple box shadows, including multiple outer box shadows to give the box a more natural feel with multiple light sources, and an inner box shadow (specified by the insetkeyword) to give the box some depth:

-webkit-box-shadow: 5px 5px 20px #000,
  1px 1px 1px #000,
  10px 10px 70px #333,
  inset 10px 10px 20px rgba(0,0,0,0.4);
box-shadow: 5px 5px 20px #000,
  1px 1px 1px #000,
  10px 10px 70px #333,
  inset 10px 10px 20px rgba(0,0,0,0.4);

이 글을 쓰는 시점에서는 사파리에서 box-shadow를 지원하려면 벤더 문자열 -webkit-이 필요합니다. 벤더 문자열이 필요한 규칙을 쓸 때는 항상 벤더 문자열 없는 선언을 마지막에 추가해서 브라우저가 벤더 문자열 없는 선언을 지원할 때는 벤더 문자열 있는 선언을 덮어쓰도록 해야 합니다.

Note: I'm including the -webkit- prefix version; as of the time of this writing, Safari still needs this for box-shadowsupport. You should always put the non-prefixed version last when using vendor prefixes, so that when browsers stop using the prefix and support the final version, the non-prefixed version will override any different behavior exhibited by the prefixed versions earlier in the source.

그래디언트

이 글을 쓰는 시점에서는 최근 브라우저 모두 벤더 문자열이 필요하므로 몇 줄을 추가해야 합니다. 우리의 블링블링 예제에서는 60도로 기울인 흰색 그래디언트를 넣어서 질감을 표현했습니다.

Linear gradients are currently supported across all of the newest browsers with vendor prefixes. We therefore need to add a few lines to get them working cross browser. For my blingtastic example, I have added a white gradient going diagonally across the box at 60 degrees to give the box a nice bit of texture:

background-image: -ms-linear-gradient(60deg, rgba(255,255,255,0),
  rgba(255,255,255,0.2) 50%, rgba(255,255,255,0));
background-image: -moz-linear-gradient(60deg, rgba(255,255,255,0),
  rgba(255,255,255,0.2) 50%, rgba(255,255,255,0));
background-image: -o-linear-gradient(60deg, rgba(255,255,255,0),
  rgba(255,255,255,0.2) 50%, rgba(255,255,255,0));
background-image: -webkit-linear-gradient(60deg, rgba(255,255,255,0),
  rgba(255,255,255,0.2) 50%, rgba(255,255,255,0));
background-image: linear-gradient(60deg, rgba(255,255,255,0),
  rgba(255,255,255,0.2) 50%, rgba(255,255,255,0));

투명도

그래디언트와 안쪽 박스 그림자에 RGBa 색상(rgba(255,255,255,0.2))을 썼습니다. 색상은 바꾸지 않고 알파 채널에서 검은색과 흰색의 투명도만 바꿨습니다. 실제 눈에 보이는 색깔은 background-color인거죠. 이런 방식에는 장점이 많습니다. 그래디언트를 지원하지 않는 브라우저에서는 배경색이 보이니까 가독성을 확보할 수 있습니다. 효과는 그대로 둔 채 background-color 값만 바꿔서 색상 스키마를 다양하게 생성할 수 있습니다.

You'll notice above that for the linear gradients and inner box shadow I've used RGBa colors, e.g., rgba(255,255,255,0.2). I'm not varying the color channels, only the alpha channel, so I'm using just pure white and black with varying transparency. The color you see is actually the background-color shining through from behind. This is a great technique in many ways: browsers that don't support linear gradients will still show a background colour, which is important for readability, and you can simply vary the background-colorvalue to create different color schemes with the effect maintained:

그림 2. 코드는 똑같고 background-color: #0000a6;만 다릅니다.

Fig. 2: The same code, but with background-color: #0000a6;.

현실로, 현실로

대단해요! 멋진 디자인을 끝냈으니 바에 가서 끝내주는 실험 결과를 보여주며 농담 따먹기를 해도 되겠죠? 음, 아직은 아닙니다. 문제가 하나 있어요. 우리 디자인은 조금 오래된 브라우저에서는 별로 좋아 보이지 않고, 정말 오래된 브라우저에서는 끔찍해 보입니다.

Great! The design looks cool, and we can go back down to the pub, to show off our groovy experiments again and perhaps break it up a bit by sniggering as we recount the World of Warcraft jokes in The Big Bang Theory. Right? Well, not really. We have a problem. The design is looking less than great in slightly older browsers, and terrible in really old browsers. What should we do?

먼저, 브라우저가 HTML5 요소를 제대로 다루게 만들려면 CSS에 display: block; 선언을 추가해야 합니다.

To start, in order to get browsers to treat the new HTML5 elements properly, we need to set them to display: block;in our CSS:

hgroup, article, header, footer, section {
  display: block;
}

다음, 인터넷 익스플로러가 HTML5 요소를 인식하고 스타일을 입힐 수 있도록 해당 요소를 직접 만들어 DOM에 추가해야 합니다.

Next, to get IE to permit styling of these unrecognized HTML5 elements, we need to create instances of them in the DOM, like so:

<script>
  document.createElement('article');
  document.createElement('section');
  document.createElement('hgroup');
  document.createElement('header');
  document.createElement('footer');
</script>

여기까지 하면 일부 구형 브라우저에서는 이렇게 보입니다.

Here's how things are looking in some older browsers:

The example as rendered in Firefox 3.6

윈도우용 파이어폭스 3.6: 웹 폰트와 텍스트 그림자는 적용됐지만 나머지는 적용되지 않았습니다.

Fig. 3: Firefox 3.6 on Windows: most of the features apart from the web fonts and text shadows are missing.

The example as rendered in Safari 4

윈도우용 사파리 4: 웹 폰트와 텍스트 그림자는 적용됐지만 나머지는 적용되지 않았습니다.

Fig. 4: Safari 4 on Windows: again, most of the features apart from the web fonts and text shadows are missing.

The example as rendered in Opera 10.60

맥용 오페라 10.60: 그래디언트는 안 나왔지만 나머지는 꽤 괜찮군요.

Fig. 5: Opera 10.60 on Mac: apart from the gradient, things are pretty good in Opera.

The example as rendered in IE9

인터넷 익스플로러 9: 대부분 지원되긴 하지만 text-shadow는 지원되지 않고, 박스 그림자도 좀 이상해 보입니다.

Fig. 6: IE 9: most of our design is there, but text-shadowis not supported, and the box shadows look weird.

The example as rendered in IE8

인터넷 익스플로러 6부터 8까지: 웹 폰트 말고는 되는게 없습니다.

Fig. 7: IE 6–8: pretty much everything is missing, except for the web fonts.

어떤 브라우저에서 테스트할지는 물론 상황에 따라 다르겠죠.

Your choice of testing browsers may vary of course, depending on your target audience and other factors.

조각 맞추기

인터넷 익스플로러를 제외한 브라우저는 자주 업그레이드 되지만 인터넷 익스플로러는 오래된 버전을 쓸 수밖에 없을 때가 잦으니 이 글에서는 주로 인터넷 익스플로러에 대해 다루겠습니다.

I am mainly going to worry about IE here, as most of the other browsers get updated pretty regularly, while IE suffers from "old version lock in" syndrome.

크로스 브라우저 문제를 해결할 가장 믿을만한 방법은 자바스크립트입니다. 네, 저도 압니다. 자바스크립트를 꺼 놓은 사람이 있을 수도 있고, 복잡한 연산 때문에 페이지가 느려질 수도 있으니 CSS 지원이 미비함을 자바스크립트로 해결하는 건 이상적인 해결책은 아니지요. 하지만 난 이렇게 생각합니다. 사용자가 자바스크립트를 끈 채로 웹을 본다면 그 사람의 웹 경험은 어차피 투박할테고, 시각 효과 몇 가지가 빠진다 한들 큰 차이는 없을 거라고요. 페이지가 느려지는 문제는 개별적으로 봐야 할 문제입니다.

Given that, the most reliable way to fix our cross browser issues is to use JavaScript. Yes, I know: it's less than ideal to use JavaScript to make up for a lack of CSS support, as some users may have it turned off, and you might also find that your pages suffer significant latency as a result of the extra number crunching. But I tend to think of it this way: if a user is browsing the web with JavaScript turned off, their web experience will be pretty crappy anyway, so the loss of a few visual effects is not going to dramatically affect them. In terms of slowing down your pages, you'll have to judge this on a case-by-case basis.

결과를 빨리 보고 싶다면 여기서 확인할 수 있습니다. 어떻게 했는지는 이제부터 설명합니다.

If you're antsy, you can test my updated version of the bling examplenow; let's talk about how I got there.

CSS3 pie

지금부터 살펴볼 도우미는 CSS3 pie인데, 이 자바스크립트 라이브러리는 구형 인터넷 익스플로러에서 border-radiusbox-shadow, 그래디언트, RGBa 색상을 지원합니다.

The main little helper we'll look at is CSS3 pie, a JavaScript library that adds support for border-radius, box-shadow, gradients, and RGBa colors to older versions of IE.

CSS Pie 사용법에 대해서는 CSS3 Pie 기초 문서를 읽어보세요. 간추리자면 CSS Pie를 내려받아 압축을 풀고, 서버에 올린 다음 인터넷 익스플로러에서 CSS Pie를 쓰려는 페이지에 다음 CSS 규칙을 추가하라는 겁니다.

Read the CSS3 Pie getting started documentationfor instructions on how to use it. The short version is that you download CSS3 pie, unzip it, upload it to your web server, then add the following declaration to all of the CSS rulesets that you want CSS3 Pie to make compatible with IE:

behavior: url(path/to/PIE.htc);

그래디언트에 쓸 background-image 속성에는 -pie- 전치사를 붙여야 합니다. 또 CSS Pie가 background-image 표기법과는 호환성이 없으므로 background로 단축해 써야 합니다. 이걸 적용하면 CSS는 다음과 같이 바뀝니다.

We also need to use a special -pie- prefixed version of the background-image property we are using to apply the CSS3 gradient, and change that particular property to read background, not background-image, as CSS3 Pie doesn't support the longhand values, just the shorthand. The new addition therefore looks like this:

-pie-background: linear-gradient(60deg, rgba(255,255,255,0),
  rgba(255,255,255,0.2) 50%, rgba(255,255,255,0));

이제 구형 인터넷 익스플로러에서는 다음과 같이 표시됩니다.

The old IE versions now render the design like this:

CSS Pie를 통해 CSS3 지원을 추가하면 인터넷 익스플로러 8에서 이렇게 보입니다.

Fig. 8: The example as rendered in IE8 with CSS3 pie used to add support for the CSS3 stuff.

실마리를 잡은 것 같은데, 배경색은 어떻게 하는게 좋을까요? CSS Pie 문서를 한동안 뒤적거려보니 CSS Pie는 인터넷 익스플로러가 RGBa 색상을 표현하게 만들기는 하지만 알파 값은 표현하지 못하고 완전히 불투명하게 렌더링한다는군요. 우리 예제에서는 반투명한 흰색을 써서 그래디언트를 표현했으니 전부 흰색이 된겁니다. 그럼 반투명한 흰색 대신 불투명한 흰색으로 -pie-background를 고쳐서 인터넷 익스플로러에서도 제대로 표현되게 해야겠군요.

Now we're getting there, but what's with the background color? The answer I found, after a little bit of digging in the CSS3 Pie docs, is that while CSS3 Pie allows IE to render RGBa colors, it can't render the alpha value; instead, it renders the RGB channels as fully opaque. We are using transparent white variants for the gradient, so it comes out as white. What we need to do here is change the -pie- prefixed backgrounddeclaration to use solid, non-transparent colors that IE can read properly.

어떤 색을 쓸 지 결정하기 위해 안쪽 박스의 box-shadow를 비활성화하고 오페라에서 연 다음 드래곤플라이의 색상 선택기로 그래디언트의 양 끝과 중간 부분의 색깔을 확인했습니다.

To work out which colors to use, I rendered my bling example in Opera with the inset box-shadowdisabled and used the Opera Dragonfly color picker utility to work out which colors were at the edges and middle of the gradient:

원래 값 #a600a6 위에 rgba(255,255,255,0) #a600a6 위에 rgba(255,255,255,0.2)
바뀐 값 #a600a6 #b630b6

색깔을 확인했으니 CSS Pie의 배경 설정을 다음과 같이 바꾸면 됩니다.

With that information, we can update the CSS3 pie background line to:

-pie-background: linear-gradient(60deg, #a600a6,#b630b6 50%, #a600a6);

이렇게 하면 “투명도” 섹션에서 얘기했던 유연한 장점을 잃어버리긴 하지만 인터넷 익스플로러에서도 다음 그림 같은 결과를 얻을 수 있습니다.

This does take away some of those flexible advantages we talked about earlier in the "Opacity" section, but it now gives us the following output in IE:

CSS Pie를 적용하고 그래디언트를 수정한 후 인터넷 익스플로러 8에서 열었습니다.

Fig. 9: The example as rendered in IE8 with CSS3 pie used and a fix for the gradient.

훨씬 낫군요! 이제 남은건 text-shadow와 박스 안쪽의 box-shadow인데 둘 다 CSS Pie에서 지원하지 않습니다. 좀 아쉽긴 하지만, 인터넷 익스플로러 구버전에서 훨씬 나아졌음에 동의할 거라 믿습니다.

Much better! So the only things we are missing now are the text-shadows and the inset box-shadow, neither of which CSS3 Pie supports. This is a bit of a pain, but I'm sure you'll agree that the result is now much nicer in old versions of IE.

이제 뭘 해야 할까요?

박스 안쪽의 box-shadow 문제는 현재 답이 없습니다. CSS Pie가 더 좋아져서 이 부분도 지원하길 기대해 봅시다. text-shadow 문제에 대해서는, CSS Pie와 매우 비슷하게 동작하면서 인터넷 익스플로러에 text-shadow 지원을 추가하는 IE CSS3라는 라이브러리가 있습니다. 마지막 예제에 IE CSS3를 추가했습니다.

I don't currently have an answer to the inset box-shadow issue; let's hope CSS3 Pie improves its range of support soon. For text-shadow, there is a library called IE CSS3 that works in a very similar way to CSS3 Pie, and can add limited text-shadowsupport to IE; I've added it into my final example:

IE CSS3 라이브러리로 text-shadow를 제한적으로 지원하게 했습니다.

Fig. 10: The final example as rendered in IE8 with limited text-shadow support via IE CSS3 library.

보시다시피 단순한 그림자만 만들 수 있으며 그림자 여러 개를 만들 수는 없으니 쓸 지 안 쓸 지는 직접 결정하십시오. 인터넷 익스플로러 전용 필터를 써서 text-shadow를 흉내낼 수도 있지만 좀 지저분하고, 성능 문제도 심합니다. 인터넷 익스플로러 전용 필터를 쓴 예제는 Cross browser box shadows를 참고하세요.

As you can see, it only works on simple text shadows, and not multiple text shadows, so take it or leave it. You could also consider faking text shadows using IE filters, but you will be labelled unclean, and they are proprietary functions that can result in an additional performance hit. See Cross browser box shadowsfor an example of IE filters in action.

그냥 jQuery를 쓰는게 낫지 않나요?

좋은 질문입니다. 자바스크립트 라이브러리를 써서 CSS3 기능을 브라우저에 상관없이 구현할 수 있습니다. 그렇게 할 능력이 있다면 그렇게 해도 되겠죠. 하지만 내 생각엔 이 방법이 더 쉽습니다. 그냥 자바스크립트 파일을 링크하고 CSS 조금 수정하기만 하면 되니까요. 자바스크립트 코드를 잔뜩 쓸 필요는 없습니다. 이 방법이 좀 더 순수하고, 스크립트를 잘 모르는 사람들(나처럼)에게 더 쉽습니다. 오래되고 성가신 브라우저를 더이상 지원할 필요가 없어질 때 까지만 쓸 임시방편이라 생각하세요.

This is a good question; you could probably achieve cross-browser support of CSS3 elements using a JavaScript library and be done with it. If you've got the skills, then go for it, but I'd argue this way is easier. All you need to do here is add some modified CSS and JavaScript links; you don't need to write a bunch of JavaScript. This makes it more pure, and certainly more accessible to those of us who aren't much good with script (like me). Think of it as a small stopgap until we don't need to support those pesky old browsers any more.

요약

이 실험이 유용했길 바랍니다. 이 예제를 더 발전시킬 아이디어가 있다면 알려주세요!

I hope you have found this exploration useful. If you have more ideas about making this blingtastic stuff work across browsers, share them in the comments! 

댓글 (857)

저자

Chris MillsChris Mills is a web technologist, open standards evangelist and education agitator, currently working at Opera Software. He spends most of his time writing articles about web standards for dev.opera.com. Outside work he is a heavy metal drummer, proud father of three and lover of good beer.