CSS 3実戦のいくつかの常用Tips

2789 ワード

本文は一部の翻訳文章で、主な内容はcss-protipsから来て、筆者自身もいくつかの自分の小さいTipsを追加しました.:not()プロパティを使用してナビゲーションに枠線を追加または除去
従来の方法は、まずliラベルごとにラベルを追加することです.
/* add border */
.nav li {
  border-right: 1px solid #666;
}

次にlast-child擬似プロパティを使用して最後の要素に作用します.
/* remove border */
.nav li:last-child {
  border-right: none;
}

代わりに、notの擬似クラスを使用して、要素の一部にのみ作用する属性を設定する必要があります.
.nav li:not(:last-child) {
  border-right: 1px solid #666;
}
bodyline-height属性を追加ph*のようなラベルに行高属性などを個別に追加する必要がある場合が多いが、代わりにbodyの属性に追加することができる.
body {
  line-height: 1;
}

このようにして、テキストクラスの要素は自動的にこの属性を継承することができます.
自動中央揃えの設定
任意の要素の自動中央揃えでflexプロパティを使用できます.
html, body {
  height: 100%;
  margin: 0;
}

body {
  -webkit-align-items: center;  
  -ms-flex-align: center;  
  align-items: center;
  display: -webkit-flex;
  display: flex;
}

カンマを使用したリストの分割
ul > li:not(:last-child)::after {
  content: ",";
}

負のnth-child属性を使用して要素を選択
li {
  display: none;
}

/* select items 1 through 3 and display them */
li:nth-child(-n+3) {
  display: block;
}

SVGをIconとして使用
.logo {
  background: url("logo.svg");
}

SVGをアイコンとして使用すると、自動スケーリングの効果が得られます.
テキスト表示の最適化
html {
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  text-rendering: optimizeLegibility;
}

単純なCSSスライダにmax-heightを使用
.slider ul {
  max-height: 0;
  overlow: hidden;
}

.slider:hover ul {
  max-height: 1000px;
  transition: .3s ease; /* animate to max-height */
}
box-sizing属性の継承
html {
  box-sizing: border-box;
}

*, *:before, *:after {
  box-sizing: inherit;
}

Table要素の等幅設定
.calendar {
  table-layout: fixed;
}

FlexboxをMargin Hacksとして使用
.list {
  display: flex;
  justify-content: space-between;
}

.list .person {
  flex-basis: 23%;
}

空のLinksにデフォルトを追加
a[href^="http"]:empty::before {
  content: attr(href);
}

iOSデバイスの要素がクリックできないことを防止
iOSデバイスでは、Clickイベントが無効になる場合があります.専用のcursorプロパティを設定する必要があります.
cursor:pointer

ただし、この属性はAndroidデバイスに設定できません.Androidデバイスに設定すると、クリックすると青い背景が表示されます.
iOSデバイスへの入力ミスフォーカスの防止
iOSデバイスでは、キーボードがイジェクトされると入力ボックスが焦げてしまう場合があります.つまり、キーボードの内容が入力ボックスに表示されない場合は、以下の上書きが必要です.
* {
  -webkit-user-select: none; /* prevent copy paste */
}

に変化
input[type="text"] {
    -webkit-user-select: text;
}