【问题标题】:My CSS style is affecting other tags which I don't want我的 CSS 样式正在影响我不想要的其他标签
【发布时间】:2020-08-27 18:21:24
【问题描述】:

我有一张带有页脚的 div 类卡片:

<div className='card'>
    <img src={thumb2} />
    <footer>
        <p>Beautifull and cozy house for you and familly</p>
        <span>$: 1200,00/month</span>
    </footer>
</div>

div 类卡片的这个页脚有如下样式:

.card footer {
    background-color: #D6E4E3;
    display: flex;
    flex-direction: column;
    align-items: center;   
    margin: 0;
    padding: 0;
}

当我在页面底部使用相同的标签页脚时,这个新标签的样式会影响我的 div 卡内的标签页脚的样式。我能做些什么来避免这种情况发生?怎样才能使用很多标签页脚且样式互不覆盖?

footer {
    height: 5%;
    display: flex;
    justify-content: center;
    background-image: linear-gradient(#5665e7, #7083E5);
}

【问题讨论】:

  • 您的问题称为specificity,并且通过为footer 使用全局元素选择器,任何footer 元素都将继承这些属性。

标签: html css styles frontend footer


【解决方案1】:

通过使用classes,您现在可以避免底部页脚的样式会影响卡片页脚。

.card--footer {
  background-color: #D6E4E3;
  display: flex;
  flex-direction: column;
  align-items: center;   
  margin: 0;
  padding: 0;
}

.page--footer {
  height: 5%;
  display: flex;
  justify-content: center;
  background-image: linear-gradient(#5665e7, #7083E5);
}
<div className='card'>
  <img src={thumb2} />
  <footer class="card--foter">
    <p>Beautifull and cozy house for you and familly</p>
    <span>$: 1200,00/month</span>
  </footer>
</div>

<footer class="page--footer"></footer>

您还可以使用这种方法轻松获得可重复使用的样式。

【讨论】:

    【解决方案2】:
    div  footer {
    background-color: #D6E4E3;
    display: flex;
    flex-direction: column;
    align-items: center;   
    margin: 0;
    

        div  footer {
        background-color: #D6E4E3;
        display: flex;
        flex-direction: column;
        align-items: center;   
        margin: 0;
        padding: 0;
    }
    padding: 0;
    

    }

    【讨论】:

    • 请不要同时添加多个答案,做一个详细而简洁的答案。
    【解决方案3】:
       .card footer {
        background-color: #D6E4E3;
        display: flex;
        flex-direction: column;
        align-items: center;   
        margin: 0;
        padding: 0;
    }
    
     <div class='card'>
                                <img src={thumb2} />
                                <footer>
                                    <p>Beautifull and cozy house for you and familly</p>
                                    <span>$: 1200,00/month</span>
                                </footer>
                            </div>
      </body>
    </html>
    

    使用类而不是类名

    【讨论】:

    • page-footer 仍将影响card-footer。这就是他的问题所在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 2020-02-20
    • 2021-11-26
    相关资源
    最近更新 更多