[英]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.似乎我放在
<button> </button>
标签之间的任何东西默认都垂直对齐到中间。 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.我发现的一种解决方法是this ,但正如您在此示例中所见( http://jsfiddle.net/d27NA/1/ ),使用这种方法,我必须手动指定包含不同长度文本的按钮的顶部属性, 否则包含较长文本的按钮将溢出顶部。
I'm wondering if there is an alternate approach that will solve this problem in a more elegant way.我想知道是否有另一种方法可以更优雅的方式解决这个问题。 Thanks.
谢谢。
html: html:
<div>
<button class="test">
This text is vertically center-aligned. I want this to be top-aligned.
</button>
</div>
css: css:
.test{
font-size:12px;
line-height:14px;
text-align:center;
height:100px;
width:100px;
}
Yup, just define the button as position:relative;
是的,只需将按钮定义为
position:relative;
and the span as position:absolute;top:0;left:0;
和span作为
position:absolute;top:0;left:0;
and you're in business. 而且你在做生意。
UPDATE UPDATE
So in the three years since this answer, flexbox has become more prominent. 所以在这个答案后的三年里,flexbox变得更加突出。 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;
您可能需要应用
appearance: none;
(with appropriate browser prefixes), but that should do it. (使用适当的浏览器前缀),但应该这样做。
You just need to change the CSS of Button and Span . 您只需要更改Button和Span的CSS。 Separate both the CSS and make following changes:
将CSS分开并进行以下更改:
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 将span的位置设置为绝对值并相应地设置top属性
Like PlantTheIdea's answer , this one adds a <span>
, but is simpler and works across browsers. 就像PlantTheIdea的回答一样,这个增加了一个
<span>
,但更简单,适用于各种浏览器。
<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.我会将 BUTTON 标记替换为 A 或 DIV,然后将其设置为看起来像一个按钮。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.