Top-align text within button element?

后端 未结 3 984
野的像风
野的像风 2020-12-07 02:29

I have some buttons that have varying numbers of lines of text, all with a fixed width and height. It seems that anything I put between the

相关标签:
3条回答
  • 2020-12-07 02:36

    You just need to change the CSS of Button and Span. Separate both the CSS and make following changes:

    button {
        display: block;
        position: relative;
    }
    
    span {
        display: block;
        position: absolute; //<-- Make it absolute
        top: 0px;           //<-- Set the top property accordingly. In this case 0px;    
    }
    

    Set the position of span as absolute and set top property accordingly

    0 讨论(0)
  • 2020-12-07 02:51

    Like PlantTheIdea's answer, this one adds a <span>, but is simpler and works across browsers.

    <div>
        <button class="test">
            <span>
                This text is vertically center-aligned. I want this to be top-aligned.
            </span>
        </button>
    </div>
    
    .test > span {
        display: block;
        height: 100%;
    }
    
    0 讨论(0)
  • 2020-12-07 03:01

    Yup, just define the button as position:relative; and the span as position:absolute;top:0;left:0; and you're in business.

    jsFiddle updated

    UPDATE

    So in the three years since this answer, flexbox has become more prominent. As such, you can do this now:

    .test {
        display: inline-flex; /* keep the inline nature of buttons */
        align-items: flex-start; /* this is default */
    }
    

    This should give you what you're looking for. You may need to apply appearance: none; (with appropriate browser prefixes), but that should do it.

    0 讨论(0)
提交回复
热议问题