【问题标题】:CSS margins not working as expectedCSS边距没有按预期工作
【发布时间】:2018-01-12 00:18:00
【问题描述】:

Angular 项目

我有一个可在特定条件下工作的可调整大小的按钮。我的问题是我觉得我的代码应该可以工作,我会解释我有什么和预期什么。

app.component.ts

<button class="button button5"> </button>

app.component.css

.button {
    background-color: #0066ff;
    border: 1px solid #0066ff;
    color: white;
    height: 60%;
    width: 60%;
    margin-left: 20%;
    margin-right: auto;
    margin-top: 20%;
    padding: 0;
}

.button5 {
border-radius: 50%;
}

index.html

<body>
  <app-root>

  </app-root>
</body>

index.html css

<style>

body, html {
    height: 100%;
    width: 100%;
    margin: 0;
}

app-root {
    display: block;
    height: 100%;
    width: 100%;
    margin: 0;
}

</style>

我的目标是创建一个按钮,它始终是页面高度的 60%,距离顶部 20%。此外,宽度为 60%,距左侧 20%。

这在某些条件下非常有效,例如.Here is my goal, unresized,但是当我稍微调整它的大小时This happens

如您所见,它不是 20%。我不知道为什么,我从来没有hard code values,而我一直是strictly using percentages,所以我认为这是万无一失的。为什么看起来顶部是 5%,底部是 35%

【问题讨论】:

  • % 总是依赖于宽度,即使是margin-top
  • 为什么这被否决了这么多?我提供了代码、图片甚至是一个有效的问题。

标签: html css button margins


【解决方案1】:

我认为您应该使用vhvw 单位(称为viewport units)。如果您总是希望屏幕上的 20% 作为边距,那么它是 20vh,其他属性也是如此。 % 总是指宽度,所以如果你调整屏幕大小,你会得到更小的宽度,从而减少边距。但使用20vh 表示屏幕高度的 20%,因此不受屏幕宽度的影响:

.button {
  background-color: #0066ff;
  border: 1px solid #0066ff;
  color: white;
  height: 60vh;
  width: 60vw; /*You can also keep 60% as % depend on width and here width of parent is equal to 100vw so you will have the same result*/
  margin-left: 20vw; /* You can also keep 20%*/
  margin-right: auto;
  margin-top: 20vh;
  padding: 0;
}

.button5 {
  border-radius: 50%;
}
&lt;button class="button button5"&gt; &lt;/button&gt;

但您似乎希望将按钮居中在屏幕中间,因此您可以依靠 flex 并避免指定边距:

body {
  height:100vh;
  margin:0;
  display:flex;
  align-items:center;
  justify-content:center;
}

.button {
  background-color: #0066ff;
  border: 1px solid #0066ff;
  color: white;
  height: 60vh;
  width: 60vw;
  padding: 0;
}

.button5 {
  border-radius: 50%;
}
&lt;button class="button button5"&gt; &lt;/button&gt;

【讨论】:

  • 对不起,我对 CSS 还没有完全了解。你是说如果我写margin-top: 20%,就是宽度的20%?我一直假设它是一个垂直分量,它指的是高度的 20%。干杯。我将研究 vh 和 vw 单位。
  • @memeKing 是的 :) 20% 是指父项的宽度,这就是调整大小时它会减小的原因。而且你也会注意到它和margin-left的值完全一样,你可以在调整大小时检查开发工具
  • 只是另一个问题,当您说 % 总是指宽度时。这适用于使用 % 符号的任何情况。所以即使我写了 height: 100% ,这是指让我的身高,我父母的宽度的 100% 吗?这是非常不直观的,这是有原因的,宽度是否为显示器/屏幕分辨率提供了很多价值? @Temani Afif
  • @memeKing 不适用于任何情况.. 例如,对于高度,height:100% 表示父级高度的 100%(如果指定)...但是当它与填充/边距一起使用时它指的是宽度......嗯,有很多情况,它们不一样,我建议你阅读更多关于相对单位的内容,你会更多地了解每种情况下的工作原理:)
  • @memeKing 这是一个有用的问题,可以解决您的问题:stackoverflow.com/questions/4982480/…
猜你喜欢
  • 1970-01-01
  • 2017-08-20
  • 2016-10-24
  • 2013-12-01
  • 2018-11-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-28
相关资源
最近更新 更多