0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【CSSのみ】checkboxをクリックで指定したclassの要素を非表示する方法

Last updated at Posted at 2022-07-09

概要

javascriptではなくcssのみを使いチェックを外すと非表示になる機能を実装しました。
チェックボックスが外れると指定したclassdisplay:none;になる仕組みです。

実装例

Sample2のチェックボックスを外すと
form3.jpg

Sample2が非表示になる。
sample2.jpg

完成コード

html

<div style="position:relative">
<input type="checkbox" class="check_button" checked>
<div class="sample">Sample1</div>
</div>
	
<div style="position:relative">
<input type="checkbox" class="check_button" checked>
<div class="sample">Sample2</div>
</div>
	
<div style="position:relative">
<input type="checkbox" class="check_button" checked>
<div class="sample">Sample3</div>
</div>
	
css
.sample{
	border: solid 1px #CCCCCC;
	padding: 10px;
	margin-bottom: 10px;
}

.check_button{
	position: absolute;
	top: 30%;
	right: 20px;
	}

.check_button:not(:checked){
    display: none;
}
	
.check_button:not(:checked)~.sample{
    display: none;
}
	

解説

チェックボックスをあらかじめcheckedにしておき、チェックボタンが外れたら非表示にする。

html
<div style="position:relative">
<input type="checkbox" class="check_button" checked>
<div class="sample">Sample2</div>
</div>

inputタグは閉じタグがないため間接セレクタ ~ を用いて非表示にしたいclassを指定する。
チェックボックスのclass:not(:checked) ~ 非表示にしたいclass

css
.check_button:not(:checked)~.sample{
    display: none;
}	

メモ

チェックだと機能的に分かりにくいので、cssを使いチェックボックスを「削除」ボタンに変更したい。
実装できたら追記します。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?