首页 > 解决方案 > 使用 CSS 居中按钮集合

问题描述

我正在使用 HTML 和 CSS 实现一个选项卡控件,并有一些模拟的 HTML 来生成一个示例表,仅用于布局目的。选项卡标题的按钮看起来不错,但有一个例外。当它们环绕时,下一行从屏幕左侧开始,即整个选项卡控件标题左对齐。

我想要的是标签标题 - 当您添加它们时 - 使用居中对齐,因此它们开始从中心向外填充页面。也就是说,如果你只有一个标题,它应该是宽度的 11%,在页面的中心。如果你有两个标题,它们应该是宽度的 11%,并且总体上它们两个应该居中。

我怎样才能做到这一点?

我的 HTML

public render() {
    return (
        <div className="Center-content">
            <div id="Home" className="Tab-content">
                 <h3>All Books</h3>
                 <p>Home is where the heart is..</p>
            </div>

            <div id="News" className="Tab-content">
                <h3>CR</h3>
                <p>Some news this fine day!</p> 
            </div>

            <div id="Contact" className="Tab-content">
                 <h3>SR</h3>
                 <p>Get in touch, or swing by for a cup of coffee.</p>
            </div>

            <div id="About" className="Tab-content">
                 <h3>CR-SR</h3>
                 <p>Who we are and what we do.</p>
            </div>

            <button className="Tab-link" >Heading1</button>
            <button className="Tab-link" >Heading2</button>
            <button className="Tab-link" >Heading3</button>
            <button className="Tab-link" >Heading4</button>
        </div>
    );
  }

我的 CSS

.Tab-link {
  background-color: #555;
  color: white;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 6px 6px;
  font-size: 14px;
  width: 11.11111%;
  border-top: 1px solid #777777;  
  border-right: 1px solid #777777;  
}

.Tab-link:hover {
  background-color: #777;
}

/* Style the tab content (and add height:100% for full page content) */
.Tab-content {
  color: white;
  display: none;
  padding: 100px 20px;
  height: 100%;
}

标签: htmlcssreactjs

解决方案


您可以只text-align: center在父元素上使用。您也可以min-width在按钮上使用而不是宽度。

.Center-content {
  text-align: center;
}

.Tab-link {
  background-color: #555;
  color: white;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 6px 6px;
  font-size: 14px;
  border-top: 1px solid #777777;
  border-right: 1px solid #777777;
  min-width: 11%;
}

.Tab-link:hover {
  background-color: #777;
}

.Tab-content {
  padding: 100px 20px;
  height: 100%;
}
<div class="Center-content">
  <div id="Home" class="Tab-content">
    <h3>All Books</h3>
    <p>Home is where the heart is..</p>
  </div>

  <div id="News" class="Tab-content">
    <h3>CR</h3>
    <p>Some news this fine day!</p>
  </div>

  <div id="Contact" class="Tab-content">
    <h3>SR</h3>
    <p>Get in touch, or swing by for a cup of coffee.</p>
  </div>

  <div id="About" class="Tab-content">
    <h3>CR-SR</h3>
    <p>Who we are and what we do.</p>
  </div>

  <button class="Tab-link">Heading1</button>
  <button class="Tab-link">Heading2</button>
  <button class="Tab-link">Heading3</button>
  <button class="Tab-link">Heading4</button>

</div>


推荐阅读