相同宽度的按钮不具有相同的宽度

Button with same width does not have same width

我在 react 应用程序中使用 styled-components。 以下是我的风格

export const SignUpNowButton = styled.button`
  background-color: #1d4ea3;
  -moz-border-radius: 28px;
  -webkit-border-radius: 28px;
  border-radius: 28px;
  color: #ffffff;
  border: 1px solid #1d4ea3;
  font-size: 17px;
  padding: 10px;
  width: 16em;
  text-align: center;
  margin-bottom: 10px;
  font-family: "SofiaProSemiBold";
`;

export const AlreadyAMemberButton = styled.div`
  background-color: #ffffff;
  -moz-border-radius: 28px;
  -webkit-border-radius: 28px;
  border-radius: 28px;
  color: #1d4ea3;
  border: 1px solid #1d4ea3;
  font-size: 17px;
  padding: 10px;
  width: 16em;
  text-align: center;
  font-family: "SofiaProSemiBold";
`;

<SignUpNowButton onClick={goToSignUp}>Sign up now</SignUpNowButton>
      <AlreadyAMemberButton onClick={goToLogin}>
        I am already a member
      </AlreadyAMemberButton>

以下是按钮的截图

我不明白为什么它们的宽度不同,因为它们具有相同的属性。

我认为某些元素是针对指定元素继承的。 “立即注册”是 styled.button 并且“我已经是会员styled.div - 而只有“立即注册”具有适当的宽度(16em 字体大小 17px 给出 272px 的宽度)。 “我已经是会员”按钮更宽了,尝试将其更改为styled.button,与“立即注册”相同“

您的页面似乎没有 CSS 规则 box-sizing: border-box。 尝试

*{
  box-sizing: border-box
}

我将尝试就为什么会发生这种情况给出一个简短的解释(链接提供了更完整的解释): 其中一个组件是样式。按钮,另一个是样式。div。所以:

按钮和 div 具有 不同的默认属性 button有一个默认的box-sizingborder-box;在大多数现代浏览器中(每个浏览器都有自己的默认值,这就是我们使用 normalize.css or reset.css 的原因)。 div 有一个默认值 box-sizingcontent-box

所以你必须以某种方式规范你的风格..选择你自己的冒险:

  • 将两者设置为相同box-sizing
  • 将它们设置为相同的 styled 类型。 style.buttonstyle.div,因此它们将继承相同的默认值。