选择后如何设置下拉列表(选择标签)的样式?

问题描述 投票:0回答:1

最好用一个例子来解释:假设我想在做出选择后将边框更改为红色而不是黑色。

这里是示例代码的链接:https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select

页面加载时,下拉列表周围有一个“正常”边框。

我做出选择后,边框宽度似乎增加了一倍。


我认为CSS可能是一个伪类,但是看看这个列表(https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes),我看不到任何可能的东西适合。

css
1个回答
0
投票

为了达到在选择后更改选择元素边框颜色的预期效果,您可以使用 :valid 伪类以及一些 CSS。这是一个例子:

<!DOCTYPE html>
<html>
<head>
<style>
/* Default styles for the select element */
select {
  border: 2px solid black; /* Default border color */
  padding: 5px;
}

/* Style for the select element when it's valid (i.e., an option is selected) */
select:valid {
  border-color: red; /* Change border color to red when an option is selected */
}
</style>
</head>
<body>

<h1>The select element</h1>

<p>The select element is used to create a drop-down list.</p>

<form action="/action_page.php">
  <label for="cars">Choose a car:</label>
  <select name="cars" id="cars" required> <!-- Note the 'required' attribute to make the select element required -->
    <option value="">Select a car</option>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
  </select>
  <br><br>
  <input type="submit" value="Submit">
</form>

<p>Click the "Submit" button and the form-data will be sent to a page on the 
server called "action_page.php".</p>

</body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.