【问题标题】:How can I color the borders of an item in a grid so that it replaces the borders of the parent container?如何为网格中的项目边框着色,以便它替换父容器的边框?
【发布时间】:2022-12-31 00:55:31
【问题描述】:

我试图通过在具有特定类时给它一个绿色边框来突出显示单个单元格。但是单元格的边框并没有替换父容器的边框。

我试图给单元格一个 1px 和纯绿色的边框。这是它的样子:My current code

【问题讨论】:

标签: javascript css reactjs


【解决方案1】:

欢迎来到堆栈溢出。如上所述,请发布您的代码,但您的图像中有足够的信息可以知道问题出在哪里。网格很棒,但开发人员通常会设计整个网格容器的样式,然后设计网格项边框的样式,以提供我们想要的样式。这是可行的,但对于悬停事件,元素位于网格内,因此如果您使用 :hover 更改边框,则子元素的边框位于父元素内。

如果您需要在悬停时突出显示一个子元素的边框,那么您必须只设置子边框的样式,而不要管父网格容器。不幸的是,有一个“陷阱”,同时设置 border-top 和 border-bottom 会给你一个双倍宽度的项目之间的边框。要解决此问题,您必须仅设置一个边框的样式,然后使用 adjacent sibling combinator 设置边框的样式。请参阅下面的注释代码:

.container {
  /* this is the parent container, we don't style any borders on this */
  width: fit-content;
  display: grid;
  grid-template-columns: 1fr;
}

.container > div {
  border: 2px solid gray;
  border-bottom-style:none; /* we have to set this to none otherwise we'll get a double thickness border between both elements */
  
  /* just some styling below to make it look like your example */
  padding: 0.5rem; 
  width: 20ch;
  text-align: center;
  font-size: 1.5rem;
}

.container > div:first-child {
  border-radius: 1rem 1rem 0 0;  /*apply fancy curving style to the top */
}

.container > div:last-child {
  border-radius: 0 0 1rem 1rem;  /* fancy styling at the bottom */
  border-bottom-style: solid; /* because this is the last element we have to add a border at the bottom */
}

.container > div:hover {
  border-color:red;
  cursor: pointer;
}

.container > div:hover + div {
  border-top-color:red;  /* we have also style the next element below's border too on hover so we use the adjacent sibling combinator (+) here. */
}
<div class='container'>
  <div>Section 1</div>
  <div>Section 2</div>
  <div>Section 3</div>
  <div>Section 4</div>
  <div>Section 5</div>
</div>

【讨论】:

    猜你喜欢
    • 2020-12-18
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多