如何居中单选按钮

4
我在网页中使用单选按钮来制作位于页面顶部的内容选项卡。我想让选项卡居中显示在屏幕上。我尝试使用 display: flex 和 text-align: justify,但没有效果。有简单的方法可以使单选按钮居中显示吗?任何帮助将不胜感激。
以下是 HTML 代码:
<body>
<div class="allTabs">
  <div class="tab">
    <input type="radio" id="tab-1" name="tab-group-1" checked>
    <label for="tab-1">Tab One</label>
      <div class="content">
         stuff 1
      </div> 
  </div>
  <div class="tab">
    <input type="radio" id="tab-2" name="tab-group-1">
    <label for="tab-2">Tab Two</label>  
    <div class="content">
       stuff 2
    </div> 
  </div> 
  <div class="tab">
    <input type="radio" id="tab-3" name="tab-group-1">
    <label for="tab-3">Tab Three</label>
    <div class="content">
       stuff 3
    </div> 
  </div> 

这是CSS。
.tabs {   
  min-height: 200px; /* This part sucks */
  clear: both;
}
.tab {
  float: left;
}
.tab label {
  background: white; 
  padding: 10px; 
  border: 1px solid #ccc; 
  margin-left: -1px; 
  position: relative;
  left: 1px;
}
.tab [type=radio] {
  display: none;   
}
.content {
  position: absolute;
  top: 28px;
  left: 0;
  background: white;
  right: 0;
  bottom: 0;
  padding: 20px;
  border-top: 4px solid #DADEDE;
  margin-top: 4px;
}
[type=radio]:checked ~ label {
  background: white;
  padding-bottom: 0px;
  border-bottom: 4px solid blue;
  margin-bottom: 5px;
  z-index: 2;
}
[type=radio]:checked ~ label ~ .content {
  z-index: 1;
}

这里是 JSFiddle 的链接:https://jsfiddle.net/mk8r6kL0/

你试过使用margin-left和right:auto吗? - Rachel Gallen
1
https://jsfiddle.net/mk8r6kL0/3/ 我不确定你想要对齐的位置。 - Rachel Gallen
首先请注意,在您的CSS中添加了样式到.tabs类,但是似乎这个类并不存在。您是不是想指的是.allTabs类? - intcreator
是的,它对齐得很好。谢谢! - Noobie123
哦,那解释了很多 :) - Noobie123
显示剩余2条评论
2个回答

5

查看此示例

.tab的CSS中删除float:left;并添加display:inline-block;

另外,添加

.allTabs {
    text-align: center;
}

针对你的CSS

因此,完整的CSS如下所示

.allTabs {
    text-align: center;
}
.tabs {
    min-height: 200px;
    clear: both;
}
.tab {
    display: inline-block;
}
.tab label {
    background: white;
    padding: 10px;
    border: 1px solid #ccc;
    margin-left: -1px;
    position: relative;
    left: 1px;
}
.tab[type=radio] {
    display: none;
}
.content {
    position: absolute;
    top: 28px;
    left: 0;
    background: white;
    right: 0;
    bottom: 0;
    padding: 20px;
    border-top: 4px solid #DADEDE;
    margin-top: 4px;
}
[type=radio]:checked ~ label {
    background: white;
    padding-bottom: 0px;
    border-bottom: 4px solid blue;
    margin-bottom: 5px;
    z-index: 2;
}
[type=radio]:checked ~ label ~ .content {
    z-index: 1;
}

谢谢@Noobie123 .. :) - Lal
哦,现在我觉得我修好了。 - Noobie123

2

移除浮动元素并尝试...

.allTabs {
    text-align: center;
}

.tab {
    display: inline-block;
}

JSfiddle 演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接