A LIST Apart: For People Who Make Websites

가변 이미지

by Ethan Marcotte

가변 그리드를 처음으로 구상했을 때 나 자신을 매우 자랑스러워 했음을 고백합니다. 가변 그리드는 복잡한 마크업도 브라우저 창의 너비에 반응해 유연하게 조절되는 레이아웃입니다. 여태까지는 가변 그리드 만으로도 모든 것이 좋아 보였습니다.

Things are looking good so far: we’ve got a grid-based layout, one that doesn’t sacrifice complexity for flexibility. I have to admit that the first time I figured out how to build a fluid grid, I was feeling pretty proud of myself.

그림 3-0. 마침내 가변 그리드를 완성했습니다. 픽셀 값을 전혀 쓰지 않으면서도 미학적 표현을 충분히 할 수 있었습니다.

Fig 3.0: Our flexible grid is finally finished. not a pixel value in sight, and we didn’t have to skimp on the aesthetics.

하지만 웹 디자인에서 흔히 그렇듯 곧 실망을 느꼈습니다. 현재 우리 페이지는 텍스트로 점철되어 있고 그 외에는 별다를 것이 없습니다. 사실은 텍스트 말고는 아무 것도 없습니다. 문제가 뭘까요? 텍스트가 가변 컨테이너 안을 매끄럽게 흐르긴 하지만, 웹 페이지에서 늘 볼 수 있는 “이미지”가 없습니다 (당신이 느꼈는지는 모르겠지만).

But then, as often happens with web design, despair set in. Currently, our page is awash in words, and little else. Actually, nothing else: our page is nothing but text. Why is this a problem? Well, text reflows effortlessly within a flexible container?and I don’t know if you’ve noticed, but the Internet seems to have one or two of those “image” things lying around. None of which we’ve incorporated into our fluid grid.

가변 레이아웃에 폭이 고정된 이미지를 넣는다면 어떻게 될까요?

So what happens when we introduce fixed-width images into our flexible design?

마크업, 마크업으로 돌아가기

답을 찾기 위해 간단한 실험을 해 보겠습니다. 블로그 모듈에 이미지를 바로 끼워넣은 다음 레이아웃이 어떻게 반응하는지 보겠습니다. 제일 먼저 할 일은 마크업에 공간을 마련하는 일이겠죠.

To find an answer, let’s do a quick experiment: let’s drop an image directly into our blog module, and see how our layout responds. The first thing we’ll need to do is to clear some space for it in our markup.

블로그 글에 자연스레 삽입된 blockquote가 기억나나요? 이 빌어먹을 페이지에는 텍스트가 너무 많으니 이미지로 바꾸겠습니다.

Remember our little blockquote, comfortably tucked into our blog article? Well, we’ve got way too much text on this darned page, so let’s replace it with an inset image:

<div class="figure">
  <p>
    <img src="robot.jpg" alt="" />
    <b class="figcaption">Lo, the robot walks</b>
  </p>
</div>

특별할 건 없습니다. img 다음에 b요소를 써서 짧지만 설명으로 충분한 제목을 붙였습니다. 의미가 분명한 HTML 5의 figure/figcaption 태그를 클래스 이름으로 썼습니다.

Nothing fancy: an img element, followed by a brief but descriptive caption wrapped in a b element. I’m actually appropriating the HTML5 figure/figcaption tags as class names in this snippet, which makes for a solidly semantic foundation.

(눈썰미가 있는 독자들은 의미 없는 b 요소를 쓴 걸 의아해 했을 수 있습니다. span 요소를 쓰는 사람도 있겠죠. 나는 의미 없이 스타일만 줄 때는 bi 같은 짧은 요소를 쓰는 편입니다.)

(Sharp-eyed readers will note that I’m using a b element for a non-semantic hook. Now, some designers might use a span element instead. Me, I like the terseness of shorter tags like b or i for non-semantic markup.)

HTML를 다 만들었으니 기본적인 CSS를 추가합시다.

With that HTML finished, let’s drop in some basic CSS:

.figure {
  float: right;
  margin-bottom: 0.5em;
  margin-left: 2.53164557%;  /* 12px / 474px */
  width: 48.7341772%;  /* 231px / 474px */
}

그림 3-1. 적당히 통통한 로봇 이미지
(courtesy of Jeremy Noble)

Fig 3.1: An appropriately botty robot pic, courtesy of Jeremy Noble.

그림에 삽입(inset) 효과를 만들었습니다. 그림은 오른쪽으로 플로트될거고 글 너비의 약 절반, 또는 가변 그리드의 네 칸을 차지할 겁니다. 마크업도 다 됐고 스타일도 다 됐습니다. 물론, 실제 쓸 이미지가 없다면 HTML과 CSS도 아무 소용이 없겠죠.

We’re creating a nice inset effect for our figure. It’ll be floated to the right, and will span roughly half the width of our article, or four columns of our flexible grid. Markup: check; style: check. Of course, all this HTML and CSS is for naught if there isn’t an actual image available.

자, 나는 당신을 너무 사랑하기 때문에(로봇도) 아무 이미지나 쓸 수는 없었습니다. 몇 분 동안 웹을 뒤적거린 끝에 끝내주는 로봇 이미지(그림 3-1)를 찾아냈습니다. 이 이미지의 뛰어난 점은 아주 크다는 겁니다. 가장자리를 조금 잘라내긴 했지만 확대나 축소는 전혀 하지 않았고 원래의 655*655 크기를 그대로 유지했습니다. 이 이미지는 자신이 들어갈 가변 컨테이너보다 훨씬 크므로 우리가 만들 가변 레이아웃이 얼마나 견고한지 보여줄 좋은 예가 될 겁니다.

Now, because I love you (and robots) dearly, not just any image will do. And after scouring the web for whole minutes, I found a fantastically imposing robo-portrait (fig 3.1). The beautiful thing about this image (aside from the robot, of course) is that it’s huge. I’ve cropped it slightly, but I haven’t scaled it down at all, leaving it at its native resolution of 655×655. This image is much larger than we know its flexible container will be, making it a perfect case to test how robust our flexible layout is.


그럼 이 거대한 이미지를 서버에 올리고, 페이지를 새로고침하고... 이런. 인터넷에서 제일 안 좋은 일이 일어났군요.

So let’s drop our oversized image onto the server, reload the page, and?oh. Well. That’s pretty much the worst thing on the internet.

그림 3-2. 이미지는 크고, 레이아웃은 깨졌습니다.

Fig 3.2: Our huge image is huge. Our broken layout is broken.

사실 이런 결과가 그다지 놀랄만한 일은 아닙니다. 레이아웃 자체가 망가진 건 아닙니다. 컨테이너는 제 구실을 하고 있고, 그리드의 열 비율도 모두 그대로 유지되어 있습니다. 하지만 이미지가 들어 있는 .figure보다 이미지가 훨씬 크므로 사용자에게는 내용이 넘쳐 보이는거죠. 이미지가 들어갈 컨테이너의 크기가 가변적이므로 이미지의 크기를 제한하는 명시적인 제약조건이 없는겁니다.

Actually, the result isn’t that surprising. Our layout isn’t broken per se?our flexible container is working just fine, and the proportions of our grid’s columns remain intact. But because our image is much wider than its containing .figure, the excess content simply overflows its container, and is visible to the user. There simply aren’t any constraints applied to our image that could make it aware of its flexible environment.

가변 이미지

그럼, 이미지의 크기를 명시적으로 제한할 수 있다면 어떨까요? 이미지가 컨테이너의 폭을 넘지 못하도록 제한할 수 있다면?

But what if we could introduce such a constraint? What if we could write a rule that prevents images from exceeding the width of their container?

누워서 떡 먹기입니다.

Well, here’s the good news: that’s very easy to do:

img {
  max-width: 100%;
}

max-width: 100%를 넣은 것 만으로 이미지가 컨테이너 밖으로 넘치지 못하게 막았습니다.

Fig 3.3: Just by including max-width: 100%, we’ve prevented our image from escaping its flexible container. On a related note, I love max-width: 100%.

리차드 러터가 처음 발견한 이 규칙은 우리 문서에 들어 있는 모든 이미지에 아주 쉽게 제한을 겁니다. 컨테이너보다 작은 img 요소는 원래 크기대로 그려집니다. 하지만 img 요소가 컨테이너보다 크면 max-width: 100% 규칙이 적용되서 이미지 너비가 컨테이너의 너비를 넘지 못하도록 제한합니다. 보시다시피 우리 로봇도 제자리를 찾았습니다.

First discovered by designer Richard Rutter, this one rule immediately provides an incredibly handy constraint for every image in our document. Now, our img element will render at whatever size it wants, as long as it’s narrower than its containing element. But if it happens to be wider than its container, then the max-width: 100% directive forces the image’s width to match the width of its container. And as you can see, our image has snapped into place.


그림 3-4. 컨테이너의 크기가 어떻게 변하더라도 이미지는 가로/세로 비율을 유지합니다.

Fig 3.4: Regardless of how wide or small its flexible container becomes, the image resizes proportionally. Magic? Who can say.

최근 브라우저는 이미지를 확대하거나 축소할 때 가로/세로 비율을 유지할 수 있습니다. 가변 컨테이너의 크기가 변함에 따라 이미지가 커지거나 작아지지만 가로/세로 비율은 유지됩니다.

What’s more, modern browsers have evolved to the point where they resize the images proportionally: as our flexible container resizes itself, shrinking or enlarging our image, the image’s aspect ratio remains intact.

아직 끝이 아닙니다. max-width: 100% 규칙은 비디오나 기타 멀티미디어 자원처럼 폭이 고정된 요소 대부분에 적용됩니다. 사실 이 규칙의 선택자를 확장해서 다른 미디어 요소에도 적용되게끔 할 수 있습니다.

I hope you’re not tired of all this good news because as it happens, the max-width: 100% rule can also apply to most fixed-width elements, like video and other rich media. In fact, we can beef up our selector to cover other media-ready elements, like so:


img,
embed,
object,
video {
  max-width: 100%;
}

그림 3-5. 다른 미디어 요소도 max-width: 100%와 매우 잘 어울려서 스스로를 유연하게 만듭니다.
내가 이 속성을 사랑한다고 얘기했던가요?

Fig 3.5: Other media play nicely with max-width: 100%, becoming flexible themselves. Did I mention I love max-width: 100%?

브라우저는 플래시 비디오나 기타 삽입된 컨텐츠, 물론 img도 공평하게 가로/세로 비율을 유지하며 크기를 바꿔 줍니다. 모두 이 간단한 max-width의 공이죠.

Whether it’s a cute little Flash video, some other embedded media, or a humble img, browsers do a fair job of resizing the content proportionally in a flexible layout. All thanks to our lightweight max-width constraint.


그럼 이제 이미지나 멀티미디어 요소를 유연하게 만드는 건 끝난거죠? CSS 규칙 하나로, 끝?

So we’ve cracked the problem of flexible images and media?right? One CSS rule and we’re done?


쉬운 일 따위는 없으므로

이제 치유의 시간입니다. 그동안 흘린 눈물, 감내해야 했던 고통, 쥐어뜯은 옷자락을 추스르며 가변 이미지의 몇가지 호환성 문제에 대해 얘기해야 합니다.

Time to let the healing begin: we need to work through the pain, the tears, the rending of garments, and talk about a few browser-specific issues around flexible images.

인터넷 익스플로러에서

인터넷 익스플로러 6과 그 이하 버전은 max-width를 지원하지 않는다는, 차가운 진실이 우리 앞에 있습니다. 7 이상? 아주 잘 지원합니다. 하지만 당신이 어쩔 수 없이 케케묵은 인터넷 익스플로러 6 또는 그 이하(쿨럭) 버전을 지원해야 한다면 방법을 더 개선해야 합니다.

The cold, hard truth is that Internet Explorer 6 and below don’t support the max-width property. IE7 version and above? Oh, it is positively brimming with support for max-width. But if you’re stuck supporting the (cough) venerable IE6 or lower, our approach needs refinement.

인터넷 익스플로러 6에서 max-width을 지원하게끔 만드는 방법은 몇가지 있습니다. 대개는 자바스크립트로 마이크로소프트 전용 expression 필터를 써서 요소의 크기를 동적으로 계산한 다음, 특정 한계를 넘으면 크기를 조절하는 방법입니다. 비표준을 감수하는 이런 방법의 예를 보고 싶다면 스벤 토프트의 클래식 블로그를 추천합니다.

Now, there are several documented ways to get max-width support working in IE6. Most are JavaScript-driven, usually relying on Microsoft’s proprietary expression filter to dynamically evaluate the width of an element, and to manually resize it if it exceeds a certain threshold. For an example of these decidedly non-standard workarounds, I’d recommend Svend Tofte’s classic blog entry on the subject.

난 어떻게 하냐구요? 나는 CSS를 씁니다. 최근 브라우저는 거의 다 max-width를 지원합니다.

Me? I tend to favor a more lo-fi, CSS-driven approach. Namely, all modern browsers get our max-width constraint:

img,
embed,
object,
video {
  max-width: 100%;
}

인터넷 익스플로러 6 전용 스타일시트에는 다음과 같이 씁니다.

But in a separate IE6-specific stylesheet, I’ll include the following:

img,
embed,
object,
video {
 width: 100%;
}

차이를 확인했나요? 인터넷 익스플로러 6 이하에는 max-width: 100% 대신 width: 100%를 씁니다.

See the difference? IE6 and lower get width: 100%, rather than the max-width: 100% rule.

경고 하나: 이 두 규칙은 완전히 다르므로 주의 깊게 사용해야 합니다. max-width: 100%는 이미지가 컨테이너의 폭을 넘지 않도록 제한하지만, width: 100%는 이미지가 컨테이너의 폭에 항상 맞게끔 강제로 맞춥니다.

A word of warning: tread carefully here, for these are drastically different rules. Whereas max-width: 100% instructs our images to never exceed the width of their containers, width: 100% forces our images to always match the width of their containing elements.

대개는 이렇게만 해도 아무 문제도 없습니다. 예를 들어 우리의 크고 아름다운 robot.jpg는 항상 컨테이너보다 크다고 간주해도 괜찮으므로 이 방법도 아주 잘 먹힙니다.

Most of the time, this approach will work just fine. For example, it’s safe to assume that our oversized robot.jpg image will always be larger than its containing element, so the width: 100% rule works beautifully.

하지만 미리보기처럼 작은 이미지나 비디오 등은 CSS로 묻지마 확대를 하기엔 적절하지 않습니다. 이런 상황에는 좀 더 명시적인 규칙을 써야 확실하겠죠.

But for smaller images like thumbnails, or most embedded movies, it might not be appropriate to blindly up-scale them with CSS. If that’s the case, then a bit more specificity might be warranted for IE:

img.full,
object.full,
.main img,
.main object {
  width: 100%;
}

페이지에 있는 고정폭 미디어에 모두 width: 100%를 적용하긴 싫다면 특정 타입의 이미지나 비디오(img.full)만 선택하도록 선택자를 쓰거나, 특정 영역 안에 있는 이미지나 비디오(.main img, .main object)만 선택해서 축소하게 할 수 있습니다. 이렇게 일부 이미지나 영역만 선택할 수 있게끔 하는 것을 화이트리스트라고 생각해 보세요. 이 목록에 들어 있는 이미지나 비디오는 모두 가변폭입니다. 목록에 없는 것은 폭이 고정된 것이죠.

If you don’t want the width: 100% rule to apply to every piece of fixed-width media in your page, we can simply write a list of selectors that target certain kinds of images or video (img.full), or certain areas of your document where you know you’ll be dealing with oversized media (.main img, .main object). Think of this like a whitelist: if images or other media appear on this list, then they’ll be flexible; otherwise, they’ll be fixed in their stodgy old pixel-y ways.

인터넷 익스플로러 구버전을 지원해야 한다면 width: 100% 규칙을 주의 깊게 써서 이미지를 가변폭으로 만들 수 있습니다. 이 이 문제는 해결했지만 아직 하나가 남았습니다.

So if you’re still supporting legacy versions of Internet Explorer, a carefully applied width: 100% rule can get those flexible images working beautifully. But with that bug sorted, we’ve still got one to go.

그 문제는 말하자면 청소 같은 거에요.

And boy, it’s a doozy.

윈도우가 우리를 싫어한다는 증거

인터넷 익스플로러 6에서 캡처한 이 그림에는 보기 싫은 계단현상이 나타납니다.
윈도우는 가변폭 이미지를 그다지 배려하지 않는 것 같네요.

Fig 3.6: Seen here in IE6, our robot image has developed some unsightly artifacts. Guess Windows doesn’t much care for our flexible images.

블로그 모듈을 몇몇 윈도우 기반 브라우저에서 보면 robot.jpg가 그다지 인상적인 모습은 아닙니다(깨져 보이죠). 그렇지만 이 문제는 브라우저의 문제라기보다는 운영체제의 문제입니다. 윈도우는 이미지 크기 조절에 능숙하지 못하거든요. 사실 윈도우에서 CSS를 통해 이미지의 크기를 조절하면 삽시간에 계단현상이 생기면서 이미지의 품질에 지대한 영향을 끼칩니다. 물론, 나쁜 영향이죠.

If you look at our blog module with certain Windows-based browsers, our robot.jpg has gone from looking imposing to looking, well, broken). But this isn’t a browser-specific issue as much as a platform-specific one: Windows doesn’t scale images that well. In fact, when they’re resized via CSS, images quickly develop artifacts on Windows, dramatically impacting their quality. And not in a good way.


그림 3-7. 특정 윈도우용 브라우저에서는 이미지가
심하게 망가져서 읽기 힘듭니다.

Fig 3.7: In certain Windows-based browsers, the image quickly develops too many artifacts to be readable.

빨리 테스트해보기 위해 텍스트가 많이 들어있는 이미지를 가변 컨테이너에 넣고 max-width: 100%로 크기를 조절했습니다. 물론 인터넷 익스플로러 6과 그 이하 버전에는 width: 100% 를 썼죠. 이렇게 글자가 많이 들어가는 이미지를 쓸 사람은 없을 겁니다. 하지만 이 이미지는 인터넷 익스플로러 7이나 그 이하 버전에서 이미지 품질이 얼마나 떨어지는지 잘 묘사합니다. 보시다시피 이미지는 - 기술적인 용어를 눈감아준다면 - 아주 흉칙합니다.역주

For a quick test case, I’ve tossed a text-heavy graphic into a flexible container, and then resized our image with the max-width: 100% fix, while IE6 and below receive the width: 100% workaround. Now, you’d never actually put this amount of text in an image. But it perfectly illustrates just how badly things can get in IE7 or lower. As you can see, the image looks?if you’ll pardon the technical term?downright nasty.

그렇지만 이미지의 크기를 자유롭게 조절하겠다는 희망을 버리기 전에, 이 버그가 윈도우용 브라우저에서 모두 일어나진 않습니다. 사실은 인터넷 익스플로러 7 이하와 윈도우용 파이어폭스 2 이하에서만 이 버그가 생기니까요. 사파리, 파이어폭스 3 이상, 인터넷 익스플로러 8 이상은 이미지 크기를 조절할 때 문제가 전혀 없습니다. 게다가 윈도우 7은 이 문제를 해결한 듯 보이니 더 좋은 소식이죠.

But before you give up on the promise of scaleable, flexible images, it’s worth noting that this bug doesn’t affect every Windows-based browser. In fact, only Internet Explorer 7 and lower are affected, as is Firefox 2 and lower on Windows. More modern browsers like Safari, Firefox 3+, and IE8+ don’t exhibit a single problem with flexible images. What’s more, the bug seems to have been fixed in Windows 7, so that’s more good news.

문제의 핵심은 찾아냈는데, 해결책이 있겠죠? 다행히 있습니다 - 파이어폭스 2는 제외하구요.

So with the scope of the problem defined, surely there’s a patch we can apply? Thankfully, there is?with the exception of Firefox 2.

파이어폭스 2는 2006년에 출시됐고 이걸 쓰는 사람은 극히 드물다고 확신합니다. 여하튼, 파이어폭스 2를 지원하려면 브라우저 탐지가 필요한데, 브라우저 탐지는 좋게 말해도 믿을 수 없죠. 설령 브라우저 탐지를 하려 해도 이 오래된 버전에는 깨져 보이는 이미지를 고칠 방법이 없습니다.

Now, this grizzled old browser was released in 2006, so I think it’s safe to assume it isn’t exactly clogging up your site’s traffic logs. At any rate, a patch for Firefox 2 would require some fairly involved browser-sniffing to target specific versions on a specific platform?and browser-sniffing is unreliable at best. But even if we did want to perform that kind of detection, these older versions of Firefox don’t have a switch that could fix our busted-looking images.

하지만 인터넷 익스플로러에는 방법이 있습니다. (다음 절 제목은 자존심 상하는데, 넘어가 주세요.)

Internet Explorer, however, does have such a toggle. (Pardon me whilst I swallow my pride for this next section title.)

AlphaImageLoader, 영웅에게 영광을

인터넷 익스플로러 6 이하에서 투명 PNG를 써본 일이 있나요? 마이크로소프트의 비표준 CSS 필터 중 하나인 AlphaImageLoader라는게 있습니다. 그 뒤에도 인터넷 익스플로러가 PNG 알파 채널을 지원하지 못하는 단점을 보완하는, 더 좋은 확장이 나왔지만(최근 나는 드류 딜러의 DD_belatedPNG 라이브러리를 씁니다.), 요소의 배경에 PNG를 쓰려고 할 땐 인터넷 익스플로러 전용 스타일시트에 다음 줄을 넣는 것이 일반적이었습니다. (≫ 표시는 페이지 폭 때문에 줄을 나눈 것이며 실제 코드는 한 줄로 써야 합니다.)

Ever tried to get transparent PNGs working in IE6 and below? Chances are good you’ve encountered AlphaImageLoader, one of Microsoft’s proprietary CSS filters. There have since been more robust patches created for IE’s lack of support for the PNG alpha channel (Drew Diller’s DD_belatedPNG library is a current favorite of mine), but historically, if you had a PNG attached to an element’s background, you could drop the following rule into an IE-specific stylesheet: (Line wraps marked ≫ ?Ed.)

.logo {
  background: none;
  filter: progid:DXImageTransform.Microsoft.AlphaImageLoader≫
  (src="/path/to/logo.png", sizingMethod="scale");
}

AlphaImageLoader는 몇 가지 일을 합니다. 첫째, 요소에서 배경 이미지를 제거한 다음 요소의 배경 계층과 내용 “사이”에 AlphaImageLoader 객체를 삽입합니다. sizingMethod 속성이 AlphaImageLoader 객체가 이미지의 컨테이너를 넘치는 부분을 잘라낼지, 일반적인 이미지로 취급할지, 컨테이너에 맞게 크기를 조절할지 결정합니다.

This AlphaImageLoader patch does a few things. First, it removes the background image from the element, then inserts it into an AlphaImageLoader object that sits “between” the proper background layer and the element’s content. But the sizingMethod property is the clever bit, dictating whether the AlphaImageLoader object should crop any parts of the image that overflow its container, treat it like a regular image, or scale it to fit it within its containing element.

거북스레 하품하는 소리가 여기까지 들리는 것 같군요. “인터넷 익스플로러 전용 PNG 패치랑 이미지 깨지는 거랑 도대체 무슨 상관이 있다는거야?”

I can hear you stifling your yawns by now: after all, what does an IE-specific PNG fix have to do with our broken image rendering?

상관이 있습니다. AlphaImageLoader를 이미지에 적용하면 이미지 렌더링 품질이 매우 좋아져서 다른 브라우저와 차이가 거의 없거든요. 게다가 sizingMethod 속성을 scale로 설정하면 AlphaImageLoader 객체가 이미지 크기를 조절하는 효과도 있습니다.

Quite a bit, as it turns out. At one point I discovered that applying AlphaImageLoader to an image dramatically improves its rendering quality in IE, bringing it up to par with, well, every other browser on the planet. Furthermore, by setting the sizingMethod property to scale, we can use our AlphaImageLoader object to create the illusion of a flexible image.

이 과정을 자동화할 자바스크립트를 만들어 놓았습니다. 스크립트를 내려받아서 가변폭 이미지가 필요한 페이지에 삽입하면 스크립트가 페이지를 훑어보고 고품질의 가변폭 AlphaImageLoader 객체를 만듭니다.

So I whipped up some JavaScript to automate that process. Simply download the script and include it on any page with flexible images; it will scour your document to create a series of flexible, high-quality AlphaImageLoader objects.

이걸 적용하면 이미지 렌더링 품질이 달라진걸 바로 알 수 있습니다. 앞의 예제에서 구제불능으로 뒤틀린 이미지를 흠잡을데 없이 렌더링된 이미지로 바꿨습니다. 게다가 크기 조절도 매우 매끄럽습니다.

And with that fix applied, the difference in our rendered images is noticeable: in our example we’ve gone from an impossibly distorted image to an immaculately rendered one. And it works wonderfully in a flexible context.

그림 3-8. 이제 이미지는 가독성도 높고 크기 조절도 잘 됩니다.
AlphaImageLoader를 조금 쓰기만 했는데 말이죠.

Fig 3.8: Our image is now perfectly legible, and resizing wonderfully. A dab of AlphaImageLoader’ll do ya.

(마이크로소프트의 비표준 필터 상당수, 특히 AlphaImageLoader에는 성능 부담이 좀 있습니다. 스토얀 스테파노프가 이에 대해 YUI 블로그에 자세히 정리해 놓았습니다. 사이트에 적용할 때는 철저히 테스트를 해서 사용자에게 어떤 영향이 있을지 점검하고, 보기 좋아진 것이 성능을 희생할 만큼 가치있는지 평가해야 합니다.)

(It’s worth mentioning that many of Microsoft’s proprietary filters, and AlphaImageLoader in particular, have some performance overhead associated with them?Stoyan Stefanov covers the pitfalls in more detail on the YUI blog. What does this mean for you? Just be sure to test the fix thoroughly on your site, gauge its effect on your users, and evaluate whether or not the improved rendering is worth the performance tradeoff.)


max-width: 100%를 쓰면 (경우에 따라 width: 100%AlphaImageLoader로 보조해서) 여러 브라우저에서 이미지가 깨끗하게 확대/축소되게 할 수 있습니다. 브라우저 창의 크기가 얼마이든 관계없이 이미지 크기는 가변 그리드의 비율에 조화롭게 변합니다.

With the max-width: 100% fix in place (and aided by our width: 100% and AlphaImageLoader patches), our inset image is resizing beautifully across our target browsers. No matter the size of the browser window, our image scales harmoniously along with the proportions of our flexible grid.

하지만 마크업에 포함되지 않은 이미지는 어쩌죠?

But what about images that aren’t actually in our markup?

유연하게 깔리는 배경 이미지

경애하는 디자이너가 블로그 모듈 목업의 새 버전을 보냈다고 가정해 봅시다. 뭔가 좀 다른데, 알아볼 수 있겠나요?

Let’s say our dearly esteemed designer sends over a revised mockup of our blog module. Notice anything different about it?

그림 3-9. 블로그 사이드바에 배경 이미지가 생겼군요. 멋집니다.

Fig 3.9: Our blog’s sidebar is now sporting a background graphic. Hot.

여태까지의 블로그 컨텐츠는 백색에 가깝고 튀지 않는 배경 위에 얹혀 있었습니다. 이젠 블로그의 왼쪽 단과 오른쪽 단이 더 분명히 구별되도록 투톤 배경을 넣게끔 디자인이 조금 바뀌었습니다. 게다가 배경을 단색으로 처리하지 않고 노이즈를 꽤 많이 넣어서 디자인에 질감을 더했습니다.

Up until now, our blog’s content has been sitting on a rather unassuming near-white background. But now the design has been modified slightly, adding a two-toned background to the blog entry to provide more contrast between the left- and right-hand columns. What’s more, there’s actually a subtle level of noise added to the background, adding an extra level of texture to our design:

그림 3-10. 배경을 수술했습니다. 자세히 보세요.

Fig 3.10: A detailed look at our new background treatment.

그러면, 새 배경 이미지를 블로그 템플릿에 넣으려면 어떻게 해야 될까요?

So: how do we actually add this new background image to our template?

2004년에 댄 시더홈이 쓴 멋진 글에는 세로로 반복되는 배경을 이용해 “가짜 단”을 만드는 방법이 설명되어 있습니다. 이 테크닉의 절묘함은 그 단순함에 있습니다. 색깔 있는 그래픽을 컨텐츠 배경에 수직으로 반복시키면 마치 같은 높이의 단이 여러 개 있는 것처럼 보이는거죠.

Back in 2004, Dan Cederholm wrote a brilliant article showing how a vertically repeating background graphic could be used to create a “faux column” effect. The technique’s genius is in its simplicity: by tiling a colored background graphic vertically behind our content, we can create the illusion of equal height columns.

댄의 원래 테크닉에서는 배경 이미지를 단순히 컨텐츠 영역의 맨 위부터 세로로 반복시켰습니다.

In Dan’s original technique, the background graphic was simply centered at the top of the content area and then tiled vertically, like so:

.blog {
  background: #F8F5F2 url("blog-bg.png") repeat-y 50% 0;
}

이것만으로도 멋지게 동작합니다. 하지만 댄의 테크닉은 고정폭 디자인을 바탕으로 그 폭에 맞게 배경 이미지를 만드는 겁니다. 가변폭 단을 두 개 쓰는 디자인에 적용할 방법이 있을까요? 기도해 봅시다...

And that technique works beautifully. But Dan’s technique assumes that your design is a fixed width, creating a graphic that matches the width of your design. Then how, pray, are we supposed to work in a background image that tiles over two flexible columns?

도흐 보우먼이란 디자이너의 연구 덕에 가변 그리드에도 가짜 단 테크닉을 적용할 수 있습니다. 계획을 조금 세우고, 친숙한 수식인 target ÷ context = result를 쓰면 됩니다.역주

Thanks to some early research by designer Doug Bowman, we can still apply the faux column technique. It just requires a little bit of extra planning, as well as a dash of your favorite formula, target ÷ context = result.

먼저 블로그 목업을 들여다보면서 흰색 배경이 회색으로 변하는 정확한 지점을 픽셀로 찾습니다. 보아하니 568픽셀 지점이 전환점이군요.

First, we’ll begin by taking a look at our mockup, to find the transition point in our background graphic, the exact pixel at which our white column transitions into the gray. And from the look of things, that switch happens at the 568 pixel mark.

그림 3-11. 568픽셀 지점에서 흰색 단이 회색으로 바뀝니다. 이 지점이 전환점입니다.

Fig 3.11: Our white column switches over to gray at the 568px mark. That’s our transition point.

전환점을 찾아냈으니 이제 우리의 가변 레이아웃에도 “가짜 단”을 적용할 수 있습니다. 이제 이 전환점을 우리 블로그 모듈 너비에 상대적인 퍼센트 값으로 바꿉니다. target ÷ context = result 공식을 쓰면 되죠. target은 전환점인 568픽셀입니다. context는 블로그 너비니까 900픽셀이죠. 이 두 값을 공식에 대입하면 됩니다.

Armed with that information, we can now adapt the “faux columns” approach to our fluid grid. First, we’ll convert that transition point into a percentage-based value relative to our blog module’s width. And to do so, our target ÷ context = result formula comes into play yet again. We have our target value of 568px, and the width of the design?our context?is 900px. And if we plug those two values into our stalwart formula:

568 ÷ 900 = 0.631111111111111

숫자가 무척 길지만 63.1111111111111%라고 쓰면 될 것 같군요.

That’s right: another impossibly long number, which converts to a percentage of 63.1111111111111%.

이 퍼센트는 잠시 옆으로 밀어놓읍시다. 이번엔 당신에게 친숙한 이미지 에디터를 실행하고, 바보스러울 만큼 큰 - 말하자면 3,000픽셀 너비의 이미지를 만듭니다. 이 이미지를 세로로 반복시킬거니까 높이는 160픽셀이면 충분합니다.

Keep that percentage in the back of your mind for a moment. Now, let’s open up your favorite image editor, and create a foolishly wide document?say, one that’s 3000 pixels across. And since we’re going to tile this image vertically, its height is only 160px tall.

그림 3-12. (곧) 배경 이미지로 바꿀 무식하게 큰 이미지입니다.

Fig 3.12: A monstrously large canvas that we’ll (shortly) turn into our background graphic.

이 이미지를 곧 배경 이미지로 바꿀 겁니다. 그런데 왜 이렇게 크게 만들었을까요? 이미지 크기가 현실적으로 가정할 수 있는 브라우저 창 크기보다 커야 되기 때문입니다. 아마.. 25세기쯤 되면 벽이 모니터가 된다든가, 아니면 홀로그램? 뭐 잘 모르겠지만 3,000 픽셀보다 큰 모니터는 당분간 나오지 않을거라 확신할 수 있습니다.역주

In a moment, we’re going to turn this blank document into our background graphic. But why is it so large? Well, this image needs to be larger than we can reasonably assume the browser window will ever be. And unless you’re reading this from the 25th century on your wall-sized display made of, I don’t know, holograms or whatever, I’m assuming your monitor’s not quite that wide.

단을 만들려면 전환점 퍼센트(63.1111111111111%) 를 새로 만든 큰 이미지에 적용해야 합니다. 3,000 픽셀 이미지를 만들었으니 퍼센트에 3,000을 곱하면 되죠.

To create the columns themselves, we’ll need to apply the transition point percentage (63.1111111111111%) to our new, wider canvas. So if we’re working with a graphic that’s 3000px across, we simply need to multiply that width by the percentage, like so:

3000 x 0.631111111111111 = 1893.333333333333

답은 1893.333333333333입니다. 포토샵은 픽셀을 소수점 단위로 다루지는 못하니 1893을 씁시다. 픽셀 정보를 알았으니 1893픽셀부터 흰색에서 회색으로 바뀌는 텍스처를 만들겠습니다.

We’re left with 1893.333333333333 as our result. And since Photoshop doesn’t deal in anything less than whole pixels, let’s round that down to 1893 pixels. Armed with that number, we’ll recreate our textures in our blank image, switching from white to gray at the 1893rd pixel.

그림 3-13. 무식하게-큰-배경 이미지에 퍼센트를 적용해서 세로로 반복할 단 이미지를 만들었습니다.

Fig 3.13: We’ve applied that percentage to our oh-so-wide background graphic, creating our tile-ready columns.

이걸 어떻게 쓸까요? 지금 한 일은 앞서 계산했던 전환점을 이 거대한 스케치북에 맞춰 커지게 한 겁니다. 이제 새로운 픽셀값을 가져다가 단을 만드는데 쓸 수 있습니다. 흰색 단은 1893픽셀이고 나머지는 회색이죠.역주

How does that help us? Well, what we’ve just done is to proportionally scale our transition point up to this new, wider canvas. So we can take that new pixel value, and use it to create our columns: the white column will be 1893px wide, with the gray column filling up the remainder.


이제 할 일은 하나뿐이죠. 스타일시트에 새 이미지를 넣으면 됩니다.

So now there’s only one thing left to do: drop our newly minted graphic into our stylesheet.

.blog {
  background: #F8F5F2 url("blog-bg.png") repeat-y 63.1111111111111% 0;
  /* 568px / 900px */
}

댄의 “가짜 단” 테크닉과 마찬가지로 배경 이미지를 블로그 맨 위에서부터 세로로 반복시켰습니다(repeat-y). background-position에 전환점의 퍼센트(63.1111111111111% 0)를 썼으므로 그리드 크기가 변해도 단은 그에 맞게 늘어나거나 줄어듭니다.

As in Dan’s original technique, we’re still positioning the graphic at the very top of our blog, and then repeating it vertically down the width of the module (repeat-y). But the ­background-position value reuses our transition point percentage (63.1111111111111% 0), keeping the columns firmly in place as our design resizes itself.

이제 가짜 단이 가변 레이아웃에서도 멋지게 동작합니다. 모든 공은 댄 시더홀름의 아이디어에 있으며 비율에 대한 생각을 조금 추가해서 구현했을 뿐입니다.

And with that, we’ve got faux columns working beautifully in a fluid layout. All thanks to Dan Cederholm’s original approach, augmented with a little proportional thinking.

그림 3-14. 가변 가짜 단

fig 3.14: Our flexibly faux columns.

완전히 가변적인 배경 이미지?

물론 우리가 만든 가변 가짜 단은 완전히 가변적인 건 아닙니다. 배경 이미지 위치를 퍼센트로 컨테이너의 크기가 변함에 따라 단의 너비도 변하는 것처럼 보이게끔 했을 뿐이죠. 이미지 크기는 전혀 변하지 않았습니다.

Of course, our flexible faux column isn’t really flexible: we’re simply using percentages to position a background image in such a way that the columns appear to resize with their container. The image’s dimensions haven’t changed at all.

하지만 레이아웃 크기에 따라 실제로 크기가 변해야 하는 배경 이미지는 어쩌죠? h1 요소에 로고를 배경 이미지로 넣어야 할 수도 있고, 사이트 내비게이션에 롤오버 효과를 줄 스프라이트가 필요할 수도 있는데요. 배경에 있어야 하는 이미지의 크기를 조절할 방법은 없을까요?

But what about a background image that actually does need to resize with the layout? Perhaps you’ve placed a logo on an h1 element’s background, or used sprites to create rollovers for your site’s navigation. Can we resize images that need to live in the background?

있다고도, 없다고도 할 수 있습니다. 일단 background-size라는 CSS3 속성이 있습니다. 이 속성을 이용하면 정말로 유연한 배경 이미지를 생성할 수 있지만, 지금 짐작하신 그대로 브라우저 지원이 아주 미숙합니다.

Well, sort of. There is a CSS3 property called background-size, which would allow us to create truly flexible background images, but?you guessed it?browser support is still pretty immature.

그때까지는 다른 방법을 써야 할텐데, 자바스크립트 기반의 독창적인 해결책이 몇 가지 있습니다. 예를 들어 스콧 로빈의 jQuery Backstretch plugin는 body 요소의 배경 이미지를 가변적으로 만듭니다. 다음 장에서 다루겠지만 CSS 3의 미디어 쿼리 기능을 이용하면 해상도별로 배경 이미지를 다르게 적용할 수 있습니다. background-size를 당장 쓸 수는 없지만, 꼬마들 말대로, 하늘이 한계입니다.역주

In the interim, there are some rather ingenious JavaScript-based solutions out there: for example, Scott Robbin’s jQuery Backstretch plugin simulates resizable background images on the body element. And as you’ll see in the next chapter, CSS3 media queries could also be used to apply different background images tailored to different resolution ranges. So while background-size might not be available yet, the sky is, as the kids say, the limit.

1. 흉칙하다는 표현을 “기술적인 용어”라고 쓴 것은 일종의 반어법으로 보입니다. 다른 표현으로 고칠까 하다가, 원저자의 뉘앙스를 존중하는게 좋겠다 싶어 그대로 씁니다.돌아가기

2. 이 테크닉은 도흐 보우먼과 에릭 마이어가 공동으로 개발한 리퀴드 블리치라는 테크닉입니다. 조금 위에서 언급한 가짜 단 테크닉과 리퀴드 블리치 모두, 7월 중에 인사이트에서 출판 예정인 Smashing CSS(제목은 바뀔 수 있습니다)에서 자세히 다뤘으므로 관심있으신 분은 조금 기다려 보세요(제가 번역했습니다).돌아가기

3. 이 문장은 “가짜 단”을 충분히 이해하지 않으면 잘 와닿지 않을 수 있습니다. 일단 끝까지 읽고 한두번 실습해보면 이해할 수 있습니다.돌아가기

4. 현재 어느정도 대중화된 모니터의 최대 해상도는 가로로 2560픽셀입니다. 브라우저 창을 3,000 픽셀보다 크게 쓸 사람은 극히 드물기는 하겠지만, 저자의 표현보다는 훨씬 일찍 그런 시기가 올 거라는 의견이 있어 덧붙입니다. (주안점은, "브라우저 창보다 큰 이미지" 입니다.돌아가기

5. 이 글은 원래 이선 마르코테가 쓰고 A Book Apart에서 출간한 <Responsive Web Design (반응형 웹 디자인)>이란 책의 3장 일부분을 발췌한 것입니다. 다음 장이라는 표현은 책의 원고였기 때문이며 이후 A List Apart에서 미디어 쿼리에 대한 내용을 다시 다룰지는 현재로서는 알 수 없습니다. <Responsive Web Design>은 국내에서 번역하여 출간 예정인 것으로 알고 있으니 관심있으신 분은 차후 검색해보시기 바랍니다.돌아가기

댓글 (6)

저자

Ethan Marcotte Ethan Marcotte is a web designer & developer who cares deeply about beautiful design, elegant code, and the intersection of the two. Over the years, Ethan has enjoyed working with such clients as the Sundance Film Festival, Stanford University, New York Magazine and The Today Show. He swears profusely on Twitter, and would like to be an unstoppable robot ninja when he grows up.