Drupalのsub-themeを使ったCSSの上書き

これまでは、Themeのstyle.cssを直接編集し、タイトルの色を変えたり、背景に画像を貼り付けたりしていました。ただし、この方法には、Themeをupdateするたびに、編集し直す必要があるという欠点があります。しかし、sub-themeの継承と上書き機能を用いると、Core ModuleやContributed themeをupdateしても、updateでIDやClassの名称が変更されない限り、CSSを編集し直す必要がないことに気付き、挑戦してみました。

この例では、danblogというthemeを継承し、mypetというthemeを作成しています。

先ず、sites/all/themes/にsub-theme用のフォルダを作ります。その中に、継承する親themeの.infoファイルをコピーし、ファイル名をsub-themeの識別名に変更し、編集します。参考文献は、“Creating a sub-theme”“Structure of the .info file”です。

nameをsub-themeの表示名に変更します。sub-themeを公開するつもりはないので、themeの説明に用いられるdiscriptionとscreenshotは削除しました。coreとengineは必須なのでそのまま残します。親themeの識別名を指定するbase themeを挿入します。regionsとfeaturesは、そのまま残した方が無難です。stylesheetsは上書き用の.cssファイルの名称に変更します。scriptsとphpは省略すれば継承されるので削除します。

name = mypet
engine = phptemplate
base theme = danblog
stylesheets[all][] = mypet.css
regions[superfish_menu] = Superfish menu
regions[preface_first] = Preface first
regions[preface_middle] = Preface middle
regions[preface_last] = Preface last
regions[content_top] = Content top
regions[left] = Left sidebar
regions[right] = Right sidebar
regions[content] = Content middle
regions[content_bottom] = Content bottom
regions[bottom_first] = Bottom first
regions[bottom_middle] = Bottom middle
regions[bottom_last] = Bottom last
regions[bottom_1] = Bottom 1
regions[bottom_2] = Bottom 2
regions[bottom_3] = Bottom 3
regions[bottom_4] = Bottom 4
regions[footer] = Footer
features[] = logo
features[] = name
features[] = slogan
features[] = mission
features[] = favicon
features[] = search
features[] = comment_user_picture
features[] = node_user_picture
features[] = primary_links
features[] = secondary_links
core = "6.x"

base themeのcssが継承されるので、mypet.cssには、上書きしたい項目のみ記入します。書き換えるID(headerとheader-wrapper)は、ブラウザーでページのソースを表示し、探しました。

#header {
  height: 120px;      /*  高さを画像に合わせます。 */
  background-image: url(P1010401.png);    /* 背景画像を指定します。 */
  background-repeat: repeat-x;      /* 背景画像をx方向に繰り返します。 */
}
 
#header-wrapper a {   
  color: #FFFFFF;      /* タイトル文字を白抜きにします。 */   
}

背景画像のファイルをこのフォルダにコピーし、Administer > Site building > ThemesでDefault Themeをこのsub-themeに変更すれば、新しいヘッダーが表示されます。