CSS :focus not working

这一生的挚爱 提交于 2019-11-30 15:17:51

If you want a real focus state to a div element, you can add a tabindex attribute to it.

.row {
	display:inline-block;
  border:1px solid grey;  
  height:200px;
  width: 200px;
  line-height:1em;
  background: grey;
  margin: 5px;
   opacity: 0.1;
}

.row:active, .row:focus { background: orange; }
 
<div id="main" class="container">
<div class="row" tabindex="1" id="row0">
</div>
</div>

If you want toggle the color with clicking the same div element, you have to use javascript (jQuery):

jQuery('#row0').click(function() {
  $(this).toggleClass('orange');
});
.row {
	display:inline-block;
  border:1px solid grey;  
  height:200px;
  width: 200px;
  line-height:1em;
  background: grey;
  margin: 5px;
   opacity: 0.1;
}

.row.orange { background: orange; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="main" class="container">
<div class="row" id="row0">
</div>
</div>

What you are looking for is :visited, but this doesn't work on a div. You should use the a-tag for it (including href="#").

.row:active, .row:visited { background: orange; }

Check the fiddle below:

http://jsfiddle.net/uuyNH/32/

Edit: Vincent G's answer seems to do more what you want though, since you can remove the background color by clicking away.

You can emulate the toggle effect with a CSS trick by adding a hidden checkbox input.

See it here

HTML :

<div id="main" class="container">
  <input type="checkbox" />
  <div class="row" id="row0">
  </div>
</div>

CSS :

.container { position: relative; }
input { position: absolute; left: 0; right: 0; top: 0; bottom: 0; width: 200px; height: 200px; z-index: 1; opacity: 0; display: block; }
input:checked + .row { background: orange; }

.row {
  display:inline-block;
  border:1px solid grey;  
  height:200px;
  width: 200px;
  line-height:1em;
  background: grey;
  margin: 5px;
  opacity: 0.1;
}

.row:active, .row:focus { background: orange; opacity:1 }
<div id="main" class="container">
<div class="row" tabindex="1" id="row0">
</div>
</div>

Please try this...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!