毎回ググってる気がする系CSSたち

まれによく使うCSS、毎回ググってる問題。
そのうちこういうのだけ集めてチートシート作りたいな〜

background-imageを横幅に合わせて可変表示する

backgroundで画像指定する際に画像の比率を保ったまま横幅いっぱいに表示する方法
横:縦の比率を計算して、縦幅%をpadding-topで指定する。
例えば400*300の画像なら、比率は100:75なのでpadding-top: 75%;を指定すればOK。
比率計算はこれが便利:比率計算機

 ■CSS
1
2
3
4
5
6
7
8
9
10
11
12
13
.header_area {
 padding-top: 75%; // 画像比率が100:75のため
 position: relative;
 
 .fade_header {
  background: url(../img/header.png) no-repeat center;
  background-size: contain;
  padding-top: 75%; // 画像比率が100:75のため
  position: absolute;
  top: 0;
  width: 100%;
 }
}

はみ出した文字は省略

■CSS
1
2
3
4
5
p {
 overflow: hidden;
 white-space: nowrap;
 text-overflow: ellipsis;
}

hover時ふわっと半透明に

■CSS
1
2
3
4
5
6
a {
 transition: opacity .3s ease;
 &:hover {
  opacity: .5;
 }
}

デバイス毎に対応CSSを変更(@support)

■CSS
1
2
3
4
5
6
7
8
9
10
11
.gradation_txt {
 background: linear-gradient(#e66465, #9198e5);
 background-clip: text;
 color: transparent;
}
@supports not (background-clip: text) {
 .gradation_txt {
  background: none;
  color: #e66465;
 }
}

first-childとfirst-of-type

■HTML
1
2
3
4
5
6
7
8
9
10
11
12
<div>
 <a href="#" class="first_child_list">ここCSSを指定するときはfirst-child</a>
 <a href="#" class="first_child_list">リンク</a>
 <a href="#" class="first_child_list">リンク</a>
</div>
<div>
 <h1>
リンクたち</h1>
<a href="#" class="first_of_type_list">ここCSSを指定するときはfirst-of-type</a>
 <a href="#" class="first_of_type_list">リンク</a>
 <a href="#" class="first_of_type_list">リンク</a>
</div>

■CSS
1
2
3
4
5
6
.first_child_list:first-child {
 // ~~
}
.first_of_type_list:first-of-type {
 // ~~
}

下向き矢印

■CSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.more_link {
 position: relative;
 
 &::after {
  border-bottom: 2px solid #aaa;
  border-right: 2px solid #aaa;
  content: '';
  height: 4px;
  margin-left: 10px;
  margin-top: 20px;
  position: absolute;
  top: 4px;
  transform: rotate(45deg);
  width: 4px;
 }
}

画像サイズを変えずに内側にborderをつける

box-sizing、存在忘れがち。
■HTML
1
2
3
4
5
6
7
8
9
10
11
<ul>
<li>
  <img src="./img/select_img1.png" />
 </li>
<li class="select_img">
  <img src="./img/select_img2.png" />
 </li>
<li>
  <img src="./img/select_img3.png" />
 </li>
</ul>

■CSS
1
2
3
4
5
6
7
8
.select_img {
 border: solid 3px #9a9a9a;
 box-sizing: border-box;
 
 .image {
  margin: -3px;
 }
}