【问题标题】:CSS to vertically align text in middle position beside a large checkboxCSS在大复选框旁边的中间位置垂直对齐文本
【发布时间】:2017-02-07 02:16:13
【问题描述】:

我想要一个 2em 高、2em 宽的复选框,并在它旁边的括号中添加一些额外的小文本:(check box to agree to these terms)

xxxxxxxxxxx
xxxxxxxxx∎x
xxxxxxx∎xxx
xxxxxx∎xxxx  (check box to agree to these terms)
x∎xx∎xxxxxx  
xxx∎xxxxxxx

#container {
  height: 3em
}
input {
  height: 2em;
  width: 2em
}
.legal {
  vertical-align: middle
}
<div id="container">
  <input type="checkbox">
  <div class="legal">(check box to agree to these terms)</div>
  <div>

通过将两者都包含在容器 div 中、设置其高度以及在文本上使用 vertical-align: middle 来使文本垂直移动,我没有任何成功。

【问题讨论】:

标签: html css vertical-alignment


【解决方案1】:

术语 div 应该有display:inline-block;,因为你想让它与复选框一致。容器应该有一个line-height 而不是height 因为vertical-align 只适用于line-height

#container {
  line-height: 3em;
  vertical-align: middle;
}
input {
  height: 2em;
  width: 2em;
  vertical-align: middle;
}
.legal {
  display:inline-block;
  width:auto;
}

https://jsfiddle.net/2twhpyy9/2/

【讨论】:

    【解决方案2】:

    有很多方法可以做到这一点 - 请参阅下面的一些方法:

    解决方案 1内联块

    inputlegal 元素使用inline-block,并将它们垂直居中对齐:

    #container {
      height: 3em
    }
    input {
      height: 2em;
      width: 2em;
      display: inline-block;
      vertical-align: middle;
    }
    .legal {
      display: inline-block;
      vertical-align: middle;
    }
    <div id="container">
      <input type="checkbox">
      <div class="legal">(check box to agree to these terms)</div>
      <div>

    方案二表格展示

    table 用于容器,table-cell 用于inputlegal 元素:

    #container {
      height: 3em;
      display: table;
    }
    input {
      height: 2em;
      width: 2em;
      display: table-cell;
      vertical-align: middle;
    }
    .legal {
      display: table-cell;
    }
    <div id="container">
      <input type="checkbox">
      <div class="legal">(check box to agree to these terms)</div>
      <div>

    解决方案 3Flexbox

    只需将flex 用于容器并使用align-items: center 将它们垂直居中:

    #container {
      height: 3em;
      display: flex;
    align-items: center;
    }
    input {
      height: 2em;
      width: 2em;
    }
    .legal {
    }
    <div id="container">
      <input type="checkbox">
      <div class="legal">(check box to agree to these terms)</div>
      <div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-11
      • 2013-07-25
      • 2010-10-04
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      相关资源
      最近更新 更多