css h1 - only as wide as the text

前端 未结 9 478
情深已故
情深已故 2020-12-24 00:08

I have an H1 style for my site:

.centercol h1 {
    color: #006bb6;
    font-weight: normal;
    font-size: 18px;
    padding:3px 3px 3px 6px;
    border-lef         


        
相关标签:
9条回答
  • 2020-12-24 00:36

    This is because your <h1> is the width of the centercol. Specify a width on the <h1> and use margin: 0 auto; if you want it centered.

    Or, alternatively, you could float the <h1>, which would make it only exactly as wide as the text.

    0 讨论(0)
  • 2020-12-24 00:38

    align-self-start, align-self-center... in flexbox

    .centercol h1{
        background: #F2EFE9;
        border-left: 3px solid #C6C1B8;
        color: #006BB6;
        display: block;
        align-self: center;
        font-weight: normal;
        font-size: 18px;
        padding: 3px 3px 3px 6px;
    }
    
    0 讨论(0)
  • 2020-12-24 00:42

    You could use a <span> instead of an <h1>.

    0 讨论(0)
  • 2020-12-24 00:50

    An easy fix for this is to float your H1 element left:

    .centercol h1{
        background: #F2EFE9;
        border-left: 3px solid #C6C1B8;
        color: #006BB6;
        display: block;
        float: left;
        font-weight: normal;
        font-size: 18px;
        padding: 3px 3px 3px 6px;
    }
    

    I have put together a simple jsfiddle example that shows the effect of the "float: left" style on the width of your H1 element for anyone looking for a more generic answer:

    http://jsfiddle.net/zmEBt/1/

    0 讨论(0)
  • 2020-12-24 00:50

    I recently solved this problem by using table-caption, though I cannot say if it is recommended. The other answers didn't seem to workout in my case.

    h1 {
      display: table-caption;
    }
    
    0 讨论(0)
  • 2020-12-24 00:50

    Somewhat like the other suggestions you could use the following code. However, if you do go the margin: 0 auto; route I'd recommend having the margin for the top and bottom of an H1 be set to something other than 0. So, perhaps margin: 6px auto; or something.

    .centercol h1{
        display: inline-block;
        color: #006bb6;
        font-weight: normal;
        font-size: 18px;
        padding:3px 3px 3px 6px;
        border-left:3px solid #c6c1b8;
        background:#f2efe9;
        display:block;
    }
    
    0 讨论(0)
提交回复
热议问题