Home > Mobile >  How to change the style of the outer element when input focus through CSS?
How to change the style of the outer element when input focus through CSS?

Time:01-09

I would like to ask, I hope that when the input box foucs, the border of the outermost search_bar can be thickened and changed color, but because the design draft needs my HTML structure as the example, so there are other ways to focus When changing the frame color and line thickness of search_bar?

.search_bar {
  display: flex;
  align-items: center;
  width: 90%;
  padding: 10px 8px;
  border-radius: 4px;
  background-color: #fff;
  border: 1px solid #222;
}
.search_bar .search_icon {
  width: 24px;
  height: 24px;
  background-image: url("https://png.pngtree.com/element_our/20200702/ourmid/pngtree-magnifying-glass-icon-image_2292648.jpg");
  background-repeat: no-repeat;
  background-size: cover;
}
.search_bar .search_input {
  width: 100%;
  border: 0px;
  margin-left: 6px;
  font-size: 16px;
}
.search_bar .search_input:focus .search_bar {
  border: 1px solid red;
}
.search_bar .enter {
  white-space: nowrap;
}
<div >
  <label for="search_input" ></label>
  <input id="keyWord"  type="text" placeholder="輸入問題關鍵字">
  <button  id="js-search">搜尋</button>
</div>

CodePudding user response:

In this case you could use a CSS pseudo-class named :focus-within, which

matches an element if the element or any of its descendants are focused

.search_bar:focus-within {
  border: 1px solid red;
}

.search_bar {
  display: flex;
  align-items: center;
  width: 90%;
  padding: 10px 8px;
  border-radius: 4px;
  background-color: #fff;
  border: 1px solid #222;
}
.search_bar .search_icon {
  width: 24px;
  height: 24px;
  background-image: url("https://png.pngtree.com/element_our/20200702/ourmid/pngtree-magnifying-glass-icon-image_2292648.jpg");
  background-repeat: no-repeat;
  background-size: cover;
}
.search_bar .search_input {
  width: 100%;
  border: 0px;
  margin-left: 6px;
  font-size: 16px;
}
.search_input:focus {
  outline: none;
}
.search_bar:focus-within {
  border: 1px solid red;
}
.search_bar .enter {
  white-space: nowrap;
}
<div >
  <label for="search_input" ></label>
  <input id="keyWord"  type="text" placeholder="輸入問題關鍵字">
  <button  id="js-search">搜尋</button>
</div>

  • Related