简体   繁体   中英

Top-align text within button element?

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 <button> </button> tags are vertically aligned to the middle by default. I want to vertically align the text within the button to the top, so that the first line of each button starts at the same line.

One workaround I found was this , but as you can see in this example ( http://jsfiddle.net/d27NA/1/ ), with this approach, I have to manually designate the top property for buttons that contain texts of different lengths, else buttons that contain longer text will overflow the top.

I'm wondering if there is an alternate approach that will solve this problem in a more elegant way. Thanks.

html:

<div>
    <button class="test">
        This text is vertically center-aligned. I want this to be top-aligned.
    </button>
</div>

css:

.test{
    font-size:12px;
    line-height:14px;
    text-align:center;
    height:100px;
    width:100px;
}

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.

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

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%;
}

I would replace the BUTTON tag with A or DIV, and then style it to look like a button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM