LoginSignup
12
5

More than 5 years have passed since last update.

背景の一部だけ色をつけたい場合のCSSスタイルシートの書き方

Last updated at Posted at 2017-08-15

ブロック全体に背景色を付けるのではなく、ブロックの一部にだけ色をつけたい、という状況があったので、方法を考えてみた。

目的:
こんな感じで、青い背景を灰色のブロックの全体ではなく、左側だけに表示したい。

image.png

2017/08/16追記

@oreoさんから紹介していただきましたが以下の方法で簡単に実現できました。

CSSの線形グラデーション(linear-gradient)
https://codepen.io/oreo/pen/jLabE

手っ取り早く動作確認したい方はこちら

やりかた

例えば、以下の図のようにブロックの左側に色をつけたい場合の指定方法。

containerというクラスの中に、background-blueという青の背景色を担当する要素とcontentsというメインのブロックがある。

背景担当のbackground-blueはabsoluteにしてcontentsと重なるようにすると、実現できる。

html
<div class="container">
  <div class="background-blue">
  </div>
  <div class="contents">
    <div>左より文字</div>
    <p>メイン コンテンツ</p>
  </div>
</div>
css
.container {
  position: relative;
  width: 200px;
  height: 300px;
  background: #dddddd;
}

.background-blue {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100px;
  background: #999;
}

.contents {
  position: relative;
}
12
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
5