html - 为什么当我在 css 上为按钮添加边距和宽度时会出现这种行为?
问题描述
当我使用margin: 10px
它width: 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>
解决方案
因为总“宽度”是 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 */
}
推荐阅读
- python-3.x - 如何在 python 中为时间序列数据中的组计算 SMAPE?
- python - 重载相等运算符
- python - 从 pyenv-virtualenv 切换到 pipenv 时保持相同的共享虚拟环境
- r - 基于多列匹配合并多个数据框
- python - 有没有办法定义依赖于内容的 CNN/Keras 接受域
- c++ - 如何在 Google Test 中为具有不同模板的多个模板类测试相同的行为?
- java - 添加的 JPanel 仅在从其他方法添加时才显示?
- java - 我可以从 Java 类文件中删除枚举值吗?
- r - 使用 R 将日志收益转换为时间序列预测的实际价格
- javascript - 将 JSON 转换为 GeoJSON 用于 Leaflet 地图的更好方法是什么