简体   繁体   English

Typescript 和 CSS:将 label 与复选框对齐

[英]Typescript and CSS : Align label with the checkbox

I am working on a project where there is a checkbox and a label, and they need to be aligned on the same line, with the text vertically aligned center to the checkbox.我正在处理一个项目,其中有一个复选框和一个 label,它们需要在同一行上对齐,文本与复选框垂直居中对齐。 But the text comes slightly below the checkbox.但是文本略低于复选框。

import React from "react";

import './checkbox.less';

interface ICheckBoxProps {
  label: string;
}

const Checkbox:React.FC<ICheckBoxProps> = ({label}) => (
    <div className="flex">
      <div>
        <input
          type="checkbox"
          id={label}
          className = "container"
        />     
        <label htmlFor={label} className="label">{label}</label> 
      </div>
    </div>
  )
export default Checkbox;

The CSS File: CSS 文件:

.App {
    font-family: sans-serif;
    text-align: center;
    position:relative;
    display: inline;
  }


.container {
    margin-bottom: 12px;
    cursor: pointer;
    font-size: 22px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    text-align: left;
    vertical-align:middle;
    display:inline-block;
    }

  
.flex{
display: flex;
align-items: center;
justify-content: flex-start;
vertical-align:middle;
display: inline-flex;
}

.label{
    display : inline;
}

Please help请帮忙

This is because you apply a margin-bottom: 12px;这是因为你应用了margin-bottom: 12px; on your <input type="checkbox"/> element (through .container class):在你的<input type="checkbox"/>元素上(通过.container类):

        <input
          type="checkbox"
          id={label}
          className = "container"
        />   
.container {
    margin-bottom: 12px;

You can simply not apply this margin on the <input> only (see label1 in below screenshot), or apply it on the containing div (that wraps both the <input> and the <label> , see label2 in below screenshot):您可以简单地不将此边距仅应用于<input> (请参见下面屏幕截图中的 label1),或者将其应用于包含 <input> 和 <label> 的 div(包装<input><label> ,请参见下面屏幕截图中的 label2):

结果

  <div className="flex">
    <div class="container2">
      <input type="checkbox" id="label2" class="container1" />
      <label for="label2" class="label">{label2 margin-bottom on containing div (both input and label)}</label>
    </div>
  </div>
.container1 {
  /*margin-bottom: 12px;*/
}

.container2 {
  margin-bottom: 12px;
}

Demo: https://jsfiddle.net/sabr7xw0/2/演示: https://jsfiddle.net/sabr7xw0/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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