【问题标题】:Align button text top left左上对齐按钮文本
【发布时间】:2018-04-05 17:29:29
【问题描述】:

如何在以下情况下(div2)使按钮文本位于左上角。

我必须使用按钮来满足一些要求,但让它看起来像一个普通的文本。任何你帮助的帮助。

容器是 flexbox 列,并且有一个带有 flex 1 的按钮。

我不想在按钮内添加元素并使其位置绝对。

需要更清洁的方式。

.container {
  display: flex;
  flex-flow: column;
  height: 200px;
  border: 1px solid gray;
}
.div1, .div3 {
  height: 40px;
}
.div2 {
  flex: 1;
  border: 1px solid red;
  text-align: left;
}
<div class="container">
   <div class="div1">
     div1
   </div>
   <button class="div2">
     I want this text to be top left
   </button>
   <div class="div3">
     div3
   </div>
</div>

【问题讨论】:

  • “左上对齐按钮文本” “使按钮文本居中” - 你想要哪个?

标签: html css flexbox


【解决方案1】:

左上对齐

使用属性flex-direction: column; 将文本左上对齐。

.container {
  display: flex;
  flex-flow: column;
  height: 200px;
  border: 1px solid gray;
}
.div1, .div3 {
  height: 40px;
}
.div2 {
  flex: 1;
  border: 1px solid red;
  text-align: left;
  flex-direction:column;
}
<div class="container">
   <div class="div1">
     div1
   </div>
   <button class="div2">
     I want this text to be top left
   </button>
   <div class="div3">
     div3
   </div>
</div>

居中对齐

只需将您的风格 text-align:left 更改为 text-align:center

.container {
  display: flex;
  flex-flow: column;
  height: 200px;
  border: 1px solid gray;
}
.div1, .div3 {
  height: 40px;
}
.div2 {
  flex: 1;
  border: 1px solid red;
  text-align: center;  
}
<div class="container">
   <div class="div1">
     div1
   </div>
   <button class="div2">
     I want this text to be top left
   </button>
   <div class="div3">
     div3
   </div>
</div>

您可以根据需要进行组合并应用属性。

【讨论】:

  • 虽然这适用于大多数浏览器。我们最喜欢的浏览器 Internet Explorer 11 不支持它。 :-/
【解决方案2】:

这并不完美,可能你将不得不玩这个,但我想这是朝着正确方向迈出的一步。

.container {
  display: flex;
  flex-flow: column;
  height: 200px;
  border: 1px solid gray;
}
.div1, .div3 {
  height: 40px;
}
.div2 {
  flex: 1;
  border: 1px solid red;
  text-align: left;
  position:absolute;
flex-direction: column;

    }
【解决方案3】:

所以,我在 .div2 分类元素中添加了 padding-bottom,因此 div2 内的文本被向上推并远离元素的底部边缘。

.container {
  display: flex;
  flex-flow: column;
  height: 200px;
  border: 1px solid gray;
}
.div1, .div3 {
  height: 40px;
}
.div2 {
  flex: 1;
  border: 1px solid red;
  text-align: left;
  padding-bottom: 40%; 
}
<div class="container">
   <div class="div1">
     div1
   </div>
   <button class="div2">
     I want this text to be top left
   </button>
   <div class="div3">
     div3
   </div>
</div>

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
  • 感谢您的反馈。我从 1 小时前就成为了 Stackoverflow 的成员,所以任何能帮助我更好地定位和未来贡献的东西都很棒。谢谢。
  • 那么,欢迎来到 Stackoverflow,Wlodzimierz!我推荐阅读How to write a good answer 和其他Help Center 文章作为一个很好的起点。在 SO 上玩得开心。
  • padding-bottom 不能解决这个问题。它在高度改变时生效。