调整按钮大小时保持相同的间隙

时间:2017-03-01 19:59:37

标签: css

我有两个并排显示的按钮。我们的想法是,无论何时屏幕宽度发生变化,按钮都会相应增大或缩小。这工作正常。但是,无论屏幕宽度是多少,我都想在按钮之间保持10px的距离。在我的情况下,随着屏幕宽度的增加,差距也会增大,我想避免。

以下是我一直在使用的测试代码:

<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<style>
body {
    margin:0;
    padding: 0;
}
div.buttons {
    width: 100%;
    box-sizing: border-box;
    padding: 0 5px;
}
a.left, a.right {
    display: block;
    width: 49%;
    box-sizing: border-box;
    background-color: #f00;
    text-align: center;
}
a.left {
    float: left;
}
a.right {
    float: right;
}

</style>
</head>

<body>
<div class="buttons">
<a class="left" href="">One</a>
<a class="right" href="">Two</a>
</div>
</body>
</html>

我可以说,给差距1%会让它随着屏幕的增长而增长,但是我试图找到一种方法,让按钮的行为符合预期,同时保持固定尺寸。

编辑添加:我正在寻找一种解决方案,它不仅可以保持间隙固定,而且还可以保持左右边距的固定。所以5px空间到边缘,按钮,10px间隙,按钮,5px空间到边缘。

感谢您提供的任何帮助。

3 个答案:

答案 0 :(得分:0)

这是因为您的链接与外边框(通过浮动)对齐,而不是彼此对齐。要按照您想要的方式更改它,移除浮动并将它们居中,再在左侧添加10px边距:

(对于该片段,我将宽度减小到48%,否则它将无法放入小屏幕中)

body {
    margin:0;
    padding: 0;
}
div.buttons {
    width: 100%;
    box-sizing: border-box;
    padding: 0 5px;
    text-align: center;
}
a.left, a.right {
    display: inline-block;
    width: 48%;
    box-sizing: border-box;
    background-color: #f00;
    text-align: center;
}
a.left {
 margin-right: 10px;
}
<div class="buttons">
<a class="left" href="">One</a>
<a class="right" href="">Two</a>
</div>

答案 1 :(得分:0)

所以这是一个新版本,满足您以后添加的额外要求。

它给出按钮的绝对位置,并通过使用calc <来定义它们的宽度,通过从外边框定义5px的左边界和右边界,从中心定义5px(最多相距10px)。 / p>

body {
    margin:0;
    padding: 0;
}
div.buttons {
    width: 100%;
    height: 1.6em;
}
a.left, a.right {
    position: absolute;
    display: block;
    background-color: #f00;
    text-align: center;
}
a.left {
 left: 5px;
 right: calc(50% + 5px);
}
a.right {
 right: 5px;
 left: calc(50% + 5px);
}
<div class="buttons">
<a class="left" href="">One</a>
<a class="right" href="">Two</a>
</div>

答案 2 :(得分:0)

我在这个fiddle中有一个解决方案。

<强> HTML

<div class="buttons">
  <div class="button-container">
    <a class="button">first</a>
  </div><div class="button-container">
    <a class="button">second</a>
  </div>
</div>

<强> CSS

.buttons {
    width: 100%;
    box-sizing: border-box;
    padding: 0;
}
.button-container {
  display: inline-block;
  width: 50%;
  box-sizing: border-box;
  border: none;
  padding: 0;
  margin: 0;
}
.button {
   display: block;
   box-sizing: border-box;
   background-color: #f00;
   text-align: center;
   padding: 5px;    
}
.button-container:nth-child(odd) .button {
  margin-right: 5px;
}
.button-container:nth-child(even) .button {
  margin-left: 5px;
}

带回家的关键点。首先,您需要避免内联块元素.button-container之间的任何空格,以避免渲染空间。否则,设置width:50%将最终换行(因为你有两个50%宽的项目有一个插入空间,这个宽度超过100%)。其次,使用.button-container允许您使用设定的百分比在页面上均匀地分割按钮。然后按钮之间的间距变为容器的内部边距。

相关问题