首页 > 解决方案 > 为什么当我在 css 上为按钮添加边距和宽度时会出现这种行为?

问题描述

当我使用margin: 10pxwidth: 100%时,我的按钮比屏幕更大,唯一的解决方案是删除边距,但我需要它。这是一个简单的演示来演示我的问题。这打破了我的应用程序的外观和感觉。

您可以在此链接https://www.w3schools.com/code/tryit.asp?filename=G7HZARR1F6M7中看到我正在尝试做什么以及我收到的奇怪行为。

.button {
  background-color: #4CAF50;
  /* Green */
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  width: 100%;
}

.without-margin {
  margin: 0px;
}

.with-margin {
  margin: 10px;
}
<div>
  <button class="button without-margin">What I want but adding margin</button>
  <button class="button with-margin">What I receive putting some margin</button>
</div>

标签: htmlcss

解决方案


因为总“宽度”是 100% + 20px(每边 10px)。
修复它的一种方法是使用calc()for width

.button {
    background-color: #4CAF50;
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    width: calc(100% - 20px); /* 100% subtracting horizontal margin */
}

推荐阅读