Clarus Dignus
Clarus Dignus

Reputation: 3897

Target select when dropdown open rather than focused (CSS or jQuery)

What I have:

A bordered select element. When the dropdown is open (i.e. focused), the bottom border is deliberately removed to achieve this look:

enter image description here

...rather than this look:

enter image description here

The difference being the two being one 1px border instead of two 1px borders between the select element and dropdown.

What I need:

I need to prevent the bottom border from being removed when the select element is tabbed into (i.e. focused but dropdown not open).

Currently, my result undesirably removes the bottom border when tabbing:

enter image description here

My code:

label,
select {
  font-size: 12px;
  font-family: sans-serif;
}

select {
  border: 1px solid #666;
  padding: 5px;
  border-radius: 0;
  color: #666;
  height: 34px;
  margin: 0;
  width: 200px;
}

select:focus {
  outline: none;
  color: #111;
  border: 1px solid #0073aa;
  background-color: rgba(0, 115, 170, 0.2);
  border-bottom: none;
}

select option {
  color: #111;
  background-color: #e8e8e8;
}
<label>Fruit:</label>
<select>
  <option value="" selected></option>
  <option value="apple">Apple</option>
  <option value="orange">Orange</option>
  <option value="banana">Banana</option>
  <option value="plum">Plum</option>
  <option value="pineapple">Pineapple</option>
</select>

Note:

I don't want to have to replace the select element (e.g. jQuery UI). I'm willing to use jQuery to target or style the select element.

Upvotes: 1

Views: 1407

Answers (1)

Bucket
Bucket

Reputation: 7521

You need to apply the styles in your select:focus selector to select:active as well, but introduce the behavior of the bottom border to the :active and :focus pseudo-selectors separately:

select:active, select:focus {
  outline: none;
  color: #111;
  border: 1px solid #0073aa;
  background-color: rgba(0, 115, 170, 0.2);
}

select:active {
  border-bottom: none;
}

select:focus {
  border-bottom: 1px solid #0073aa;
}

This way when you tab over or click on the dropdown, the styles are applied, sans the bottom border style. Since clicking makes the element active but tabbing does not, we need to make sure the bottom border shows up when we simply have focus on the select.

Upvotes: 1

Related Questions