CSS3でボックスの高さで可変する45度の角度のグラーデーション

CSS3のgradientでは対角にグラデーションを引くことはできるけど角度を指定してグラデーションを引くことができません。そこで無理やり角度を付けてグラデーションを引く方法を考えてみました。

がんばったんですがネタレベルを超えられなかったので注意してください。
追記を行っていたら結構いい感じのサンプルが出来上がりました。

まずは次のようなHTMLを用意。

<section class="hoge">
	<img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==">
	<div>
		テキスト(中略)テキスト
	</div>
</section>

これに対して次のようなCSSを適用させると45度のグラデーションが引けます。

.hoge{
	margin:14px;
	position:relative;
	z-index:1;
	background:red;
	overflow:hidden;
}
.hoge>img{
	position:absolute;
	height:100%;
	background-image:-webkit-gradient(linear, right bottom, left top, color-stop(0,red), color-stop(0.5, red), color-stop(1, white));
	z-index:0:
}
.hoge > div{
	position:relative;
	z-index:1;
	width:100%;
	color:white;
	text-shadow: 0 1px 0 rgba(255, 0, 0,1);
}

サンプル(WebKitオンリー!)

高さが大きくなるとグラデーションが大きくなります。

ポイントはdata URIスキームで配置している1×1の透過gif。height:100%でボックスの高さに合わせて可変する正方形になるので対角線にグラデーションを設定すれば45度のグラーデーションが書けるわけです。

透過gifの縦横比を調整すれば他の角度のグラーデーションも書けます。

透過gif用のimg要素を書くのは気が引けるのですが、装飾用の画像と考えaltを記入しなければいいはず(キリッ。

:befreとcontentでの追加も考えたんですが、contentで追加した画像は縦横比を保って拡大されない。

現在は高さ基準でグラデーションを設定してますが、.hoge>imgのheight:100%をwidth:100%に変えれば横幅基準になるはず。

補足

サイズが固定の場合なら、data URIスキームを利用しなくても次のようなCSSでグラデーションの角度が指定できます。

.hoge{
	margin:14px;
	position:relative;
	z-index:1;
	background:red;
	overflow:hidden;
}
.hoge:before{
	position:absolute;
	content:"";
	display:block;
	background-image:-webkit-gradient(linear, right bottom, left top, color-stop(0,red), color-stop(0.5, red), color-stop(1, white));
	width:200px;
	height:200px;
	z-index:0:
}
.hoge > div{
	position:relative;
	z-index:1;
	width:100%;
	color:white;
	text-shadow: 0 1px 0 rgba(255, 0, 0,1);
}

サンプル

角度は.hoge:beforeのwidthとheightで調整してください。

補足の追記

角度はtransformのrotateで制御したほうがいいかも。

.hoge:before{
	position:absolute;
	content:"";
	display:block;
	background-image:-webkit-gradient(linear, left bottom, left top, color-stop(0,red), color-stop(0.5, red), color-stop(1, white));
	width:1000px;
	height:400px;
	z-index:0;
	-webkit-transform-origin:center top;
	-webkit-transform:translate(-500px,0) rotate(-45deg);
}

サンプル

補足の追記の追記

あれ、じゃ次のようにすると、高さにより変わり特定角度のグラデーションが引けるんじゃないの?

.hoge:before{
	position:absolute;
	content:"";
	display:block;
	background-image:-webkit-gradient(linear, left bottom, left top, color-stop(0,red), color-stop(0.5, red), color-stop(1, white));
	width:500%;
	height:150%;
	z-index:0;
	-webkit-transform-origin:center top;
	-webkit-transform:translate(-50%,0) rotate(-45deg);
}

サンプル
これが当初の目的のもの!!追記していくうちに出来上がりました!

スポンサードリンク

«現場のプロから学ぶXHTML+CSS 増刷(12刷)決定 | メイン | HTML5が使えるスマートフォンOS»