javascript - 并排和水平对齐两个div

标签 javascript html css

我正在尝试对齐两个 <div>并排放置,并将它们对齐在同一行。一个包含一个复选框,该复选框使用 CSS 更改为切换按钮,另一个包含纯文本。问题是当我试图让它们并排放置时,它们的内容没有正确垂直对齐。切换按钮高于第二个 <div> 中的文本.

这是我的代码:

.switch {
  position: relative;
  display: inline-block;
  width: 47px;
  height: 25px;
}

.switch input {
  display: none;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
  border-radius: 34px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 17px;
  width: 17px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
  border-radius: 50%;
}

input:checked+.slider {
  background-color: #2196F3;
}
<div style="float:left;">
  <div style="float: left;">
    <p id="show_crash_toggle_text" style="font-size:20px;" <b>User</b>&emsp;</p>
  </div>
  <div style="margin-left: 60px;">
    <label class="switch">
          <input type="checkbox" onclick = "show_crash_log()">
          <span class="slider"></span>
        </label>
  </div>
</div>
<div style="margin-left:150px;">
  <b style="font-size:20px">Search by: </b>
</div>

这里有一些显示问题的图像。


最佳答案

如果你使用 flexbox,你可以使用 align-items: center,来水平对齐 div。

.flex-container {
  display:flex;
  align-items: center;
}

.switch {
position: relative;
display: inline-block;
width: 47px;
height: 25px;
}

.switch input {display:none;}

.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
border-radius: 34px;
}

.slider:before {
position: absolute;
content: "";
height: 17px;
width: 17px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
border-radius: 50%;
}

input:checked + .slider {
background-color: #2196F3;
}
<div class="flex-container">
    <p id="show_crash_toggle_text" style="font-size:20px;"><b>User</b></p>
  <div>
    <label class="switch">
      <input type="checkbox" onclick = "">
      <span class="slider"></span>
    </label>
  </div>
<b style="font-size:20px">Search by: </b>
</div>

关于javascript - 并排和水平对齐两个div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54110815/

相关文章:

javascript - jQuery 将操作应用于被注入(inject)的元素

javascript - 以编程方式选择内容可编辑的 HTML 元素中的文本?

jquery - 水平显示下拉菜单

javascript - 如何根据需要适当调整 dijit/确认对话框的大小

CSS 关键帧 : How to move div to certain position

CSS Flexbox动态宽高比代码受内容影响

javascript - 是否可以向现有对象添加构造函数?有意义吗?

javascript - Bootstrap 模式中的 SlickGrid 仅显示前两列数据

html - 嵌套元素的 CSS 和覆盖样式

javascript - HTML5 Canvas - 从左上角绘制圆圈