【问题标题】:Anchor and button elements render differently with same stylesAnchor 和 button 元素在相同样式下呈现不同
【发布时间】:2022-01-14 21:57:58
【问题描述】:

正如标题所说—— 我将锚点和按钮设置为 flex,但它们的大小不同。 为什么会这样?如何在具有自动宽度的两个元素上实现相同的视觉效果?

a,
button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: auto;
  background: orange;
  margin-bottom: 20px;
  padding: 10px;
  height: 50px;
  margin: 0;
}
<a href="#">asdf</a>
<button>asdf</button>

【问题讨论】:

  • 锚标签和按钮有不同的固有风格。这使得它呈现不同。使用 flex: 1/2 或类似的东西来实现它
  • @RajeshPaudel 在这种情况下 abutton 是一个弹性容器。我应该在什么元素上使用flex: 1/2
  • 对不起,我的意思是说你需要使用 flex: 1/2 如果它在里面。但这种行为主要是由于两个盒子大小。内容框和边框。
  • 如果它是 box-sizing,那么将其设置为一个或另一个值会有所帮助。但可悲的是,它不是:(

标签: html css flexbox


【解决方案1】:

这个问题是由于 button 不允许有一些其他的显示属性,具体取决于引擎。将button 包裹在span 中是最简单的解决方案。

<a href="#">asdf</a>
<span><button>asdf</button></span>
a, span {
  display: flex;
  align-items: center;
  justify-content: center;
  width: auto;
  background: orange;
  margin-bottom: 20px;
  padding: 10px;
  height: 50px;
  margin: 0;
}

【讨论】:

  • 这真的不是一回事
  • 小心解释为什么@Huangism
  • 你的按钮是一个弹性项目,其中 OP 的按钮是弹性容器
  • 好吧,他们没有指定它必须是一个弹性容器。
【解决方案2】:

这取决于引擎,但在浏览器中最可能的原因是 css 的 box-sizing 属性。 MDN 将框尺寸定义为

默认情况下,在 CSS 盒子模型中,您分配给 element 仅应用于元素的内容框。如果元素 有任何边框或填充,然后将其添加到宽度和高度 到达屏幕上呈现的框的大小。这 意味着当你设置宽高时,你必须调整值 您给予允许可能添加的任何边框或填充。为了 例如,如果您有四个宽度为 25% 的框;如果有剩余或 右填充或左或右边框,默认情况下它们不适合 在父容器的约束内的一行。

您可以在此处阅读更多相关信息:https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing 如何使用

但您可以达到的最接近的方法是使用宽度作为继承。这将导致元素从父级继承宽度。

// Resetting both to have same type for similar render
a,button {
  box-sizing: content-box;
  border: unset;
}

a,
button {
  display: flex;
  align-items: center;
  justify-content: center;

  background: orange;
  margin-bottom: 20px;
  padding: 10px;
  height: 50px;
  margin: 0;
}

// Add width to parent element
.w-100 {
   width: 100vw;
}
// This will cause the default width behaviour to inherit from parent
a,button {
  width: inherit;
}
<div class="w-100">
  <a href="#">asdf</a>
  <button>asdf</button>
</div>

【讨论】:

  • 在 Mac 上看不到 chrome 的差异
【解决方案3】:

我的问题由两部分组成:

  1. buttona 呈现不同
  2. 我想让a 在这个例子中像button 一样渲染。所以我正在设计的组件不会让它的用户包装它等等。

正确答案是将width 属性设置为fit-content。它有很好的浏览器支持,我会尝试使用它。

非常感谢您的回答!

【讨论】:

  • 这是一个答案吗?如果是这样,请更清楚地证明什么是有效的。
【解决方案4】:
Here, in `width:auto`, auto tells the default value. The browser calculates the width.

两者也是不同的元素。

div {
  display: flex;
  flex-direction: row;
  justify-content: space-evenly;
 align-items: center;
}
a, 
button {
  width: auto;
  background: orange;
  padding: 30px;
  margin: 0;
}
a {
  padding-bottom:31px;
}
<div>
  <a href="#">asdf</a>
  <button>asdf</button>
</div>

【讨论】:

  • OP 询问锚点和按钮何时显示为弹性,而不是作为弹性项目
  • 这是真的,但是来吧,问题很明显,比较锚和按钮时都是弹性容器
猜你喜欢
  • 1970-01-01
  • 2020-08-14
  • 2018-08-14
  • 2017-01-07
  • 2019-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-10
相关资源
最近更新 更多