Tips
input要素に疑似要素で悩む
デザインとして検索窓のsubmitボタンを装飾するためにボタンを「ルーペアイコン」にしようと次のコードを記述しました。
<form role="search" method="get" action="<?php echo home_url('/'); ?>" autocomplete="off">
<div class="search_form_wrapper">
<div><input type="text" class="search_input" name="s" id="s" value="" required placeholder="検索">
<input type="hidden" value="<?php echo get_post_type(); ?>" name="post_type" id="post_type"></div>
<input type="submit" class="search_button">
</div>
</form>
.search_form_wrapper .search_button {
width: 20px;
height: 20px;
padding-right: 30px;
appearance: none;
-webkit-appearance: none;
background: none;
border: none;
border-radius: 0;
box-shadow: none;
outline: none;
font: inherit;
color: #fff;
text-decoration: none;
padding: 0;
margin: 0;
cursor: pointer;
display: inline-block;
position: absolute;
top: 8px;
right: 10px;
}
.search_form_wrapper .search_button:after {
content: "";
display: block;
width: 20px;
height: 20px;
background-image: url("../images/icon_search_btn.svg");
background-repeat: no-repeat;
background-size: cover;
position: absolute;
top: 0;
left: 0;
}
しかし、これが全く思い通りの表示にならない。疑似要素が表示されないのです。
このエラーの原因と解決方法を解説します。
原因はinput要素が置換要素(replaced element)で内部コンテンツを持たないために疑似要素が表示されないことが判明。
疑似要素 ::beforeや::after は、要素の「内部」に仮想的な子要素を生成するために、擬似用をを挿入する「内部」が存在しないため表示されないのが実装上の理由です。
解決策
<button> を使う
button は通常要素なのでinput要素とは違い、疑似要素が使えます。
<form role="search" method="get" action="<?php echo home_url('/'); ?>" autocomplete="off">
<div class="search_form_wrapper">
<div><input type="text" class="search_input" name="s" id="s" value="" required placeholder="検索">
<input type="hidden" value="<?php echo get_post_type(); ?>" name="post_type" id="post_type"></div>
<button type="submit" class="search_button"></button>
</div>
</form>
.search_form_wrapper .search_button {
width: 20px;
height: 20px;
padding-right: 30px;
appearance: none;
-webkit-appearance: none;
background: none;
border: none;
border-radius: 0;
box-shadow: none;
outline: none;
font: inherit;
color: #fff;
text-decoration: none;
padding: 0;
margin: 0;
cursor: pointer;
display: inline-block;
position: absolute;
top: 8px;
right: 10px;
}
.search_form_wrapper .search_button:after {
content: "";
display: block;
width: 20px;
height: 20px;
background-image: url("../images/icon_search_btn.svg");
background-repeat: no-repeat;
background-size: cover;
position: absolute;
top: 0;
left: 0;
}
実務的な結論
ボタンを装飾したいボタンならinput要素ではなくbutton要素にするのが、標準的な実装方法です。CSS的にもアクセシビリティ的にも扱いやすいですので、この実装方法一択としましょう。

コメントを残す