代码之家  ›  专栏  ›  技术社区  ›  user979331

CSS文本装饰下划线,宽度与文本和下划线相同

  •  0
  • user979331  · 技术社区  · 4 年前

    #login h1 {
        color: #FFF;
        border-bottom: 2px solid #15b6e5;
        text-transform: uppercase;
        font-weight: 700;
        text-align: center;
        display: table-cell;
    }
    

    现在我试着把它居中,我试着添加一个包装器并添加display:table,它使它居中,但是下划线的宽度与文本不同:

    #login .heading-wrapper {
        display: table;
        width: 100%;
    }
    

    这是HTML

    <div class="col-md-12 heading-wrapper">
                <h1>Login</h1>
            </div>
    

    3 回复  |  直到 4 年前
        1
  •  1
  •   gavgrif    4 年前

    问题是h1是一个块级别的元素,因此会拉伸以填充父容器。你需要做的是要么-使h1不是块级元素并居中-或者将文本放在h1内的一个范围内,然后将其居中,然后在跨度上应用边框底部。

    .example-1 .heading-wrapper {
      text-align: center;
      }
    
    .example-1 h1 {
        color: #000;
        border-bottom: 2px solid #15b6e5;
        text-transform: uppercase;
        font-weight: 700;
        display: inline-block;
    }
    
    .example-2 h1 {
        color: #000;
        text-transform: uppercase;
        font-weight: 700;
        text-align: center;
    }
    
    .example-2 h1  span{
        border-bottom: 2px solid #15b6e5;
    }
    <span>example 1 - h1 display: inline-block</span>
    
    <div class="example-1">
      <div class="col-md-12 heading-wrapper">
          <h1>Login</h1>
      </div>
    </div>
    
    
    <span>example 2 - span within h1</span>
    
    <div class="example-2">
      <div class="col-md-12 heading-wrapper">
          <h1><span>Login</span></h1>
      </div>
    </div>
        2
  •  0
  •   David    4 年前

    https://css-tricks.com/snippets/css/a-guide-to-flexbox/ .

    .center {
      width: 100%;
      padding: 20px 0;
      display: flex;
      justify-content: center;
      background-color: #cfd2d6;
    }
    
    .center h1 {
      text-decoration: underline;
    }
    <div class="center">
      <h1>Login</h1>
    </div>