两个按钮各占一半

476 阅读2分钟

需求:两个按钮各占一半

 
<div className="button-box">
    <button className="half-button">按钮1</button>
    <button className="half-button">按钮2</button>
</div>
  
export default

方案一: 设置宽度为50%

在html中buttondisplay属性是inline-block,也就是说button是行内元素,而且能正确解释盒模型。所以我们直接设置按钮宽度为50%。

.button-box{
  width: 100%;
}
.half-button{
  display: inline-block; // button默认值,不用写
  width: 50%
}
//使用tailwind
<div className=" w-full">
  <button className=" w-1/2">按钮1</button>
  <button className=" w-1/2">按钮2</button>
</div>

根据这个思路,当我们遇到div各占一半的需求也可以这样实现

<div className="div-box">
  <button className="half-div">div 1</button>
  <button className="half-div">div2</button>
</div>
.div-box{
  width: 100%;
}
.half-div{
  display: inline-block; 
  width: 50%
}

当然。div各占一半还有其他解决办法,这里不多赘述。接下来的解决方案也可以解决div各占一半的需求。

方案二:display: flex + flex-grow

使用flex + flex-grow搭配实现

.button-box{
  display:flex;
}
.half-button{
  flex-grow: 1;
  text-align: center;
}

当我们使用flexbox布局时,如果我们的flex-grow值相同,那么空间将会被平均分配,如果一个元素的flex-grow值更大,那么它被分配的空间也更大。

//tailwind.css
<div className=" flex">
  <button className=" flex-grow">按钮1</button>
  <button className=" flex-grow">按钮2</button>
</div>

方案三: display: grid

.App.css

.button-box{
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-columns: repeat(2 , 1fr);
}

grid代表网格布局,grid-template-columns用于定义网格的列数和列宽。

//tailwind.css
<div className=" grid grid-cols-2">
  <button>按钮1</button>
  <button>按钮2</button>
</div>

简单说一下grid-template-columns

grid-template-columns使用

1、平均分栏布局

.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

.grid-container元素分为3列,每列平均分配宽度。

2、指定宽度布局

.grid-container {
  display: grid;
  grid-template-columns: 200px 1fr 300px;
  gap: 20px // 网格布局的行与列间隙的尺寸。
}

.grid-container元素分为3列,第1列宽度为200像素,第2列占剩余空间的比例为1,第3列宽度为300像素。

3、使用网格线进行分割

.grid-container {
  display: grid;
  grid-template-columns: [col1-start] 200px [col2-start] 1fr [col2-end col3-start] 300px [col3-end];
}

使用了方括号指定了网格线的名称,可以在布局中使用这些名称来进行对齐和定位。

以上就是我想到的按钮各占一半的解决方案, 你还有什么其他的解决方案吗?快来告诉我呀。