gpt4 book ai didi

html - 哪个魔术 CSS 导致

转载 作者:技术小花猫 更新时间:2023-10-29 12:14:43 24 4
gpt4 key购买 nike

我发现<button>里面的文字自动垂直居中,而 <div> 内的文本顶部对齐。

我试图找出造成差异的 CSS 规则但失败了。

div,
button {
width: 4em;
height: 4em;
background-color: red;
padding: 0;
border: 0;
margin: 1em;
font-size: 1em;
font-family: Arial;
}

div {
text-align: center;
display: inline-block;
cursor: default;
box-sizing: border-box;
}
<div>text text</div>
<button>text text</button>

<div>text text text text</div>
<button>text text text text</button>

<div>text text text text text text</div>
<button>text text text text text text</button>

对于上面的例子,比较所有从 Chrome 计算的 CSS 规则,我只能找到一对不同的 -- align-items: stretch对于 <div>同时align-items: flex-start对于 <button> .

但是分配 align-items: flex-start没有帮助。所以我完全糊涂了。

令我困惑的是<div> 之间的文本垂直对齐方式不同|和 <button>即使您将所有 CSS 规则设置为相同的对应值。 换句话说,使用相同的 CSS 规则,<div><button>表现不同。为什么?

引擎盖下的魔法是什么?


我可以在 <div> 中垂直居中文本(下面的例子)。我只是好奇是什么导致了文本垂直对齐之间的差异。

也许这不是由特定的CSS规则引起的,而是因为这两个元素在浏览器中的布局算法不同?

div,
button {
width: 4em;
height: 4em;
background-color: red;
padding: 0;
border: 0;
margin: 1em;
font-size: 1em;
font-family: Arial;
}

div { /* basic CSS rules to button-fy */
text-align: center;
display: inline-block;
cursor: default;
box-sizing: border-box;
}

/* Magic */
div, button {
vertical-align: middle;
}

div span {
display: inline-block;
position: relative;
top: 50%;
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
}
<div><span>text text</span></div>
<button>text text</button>

<div><span>text text text text</span></div>
<button>text text text text</button>

<div><span>text text text text text text</span></div>
<button>text text text text text text</button>

最佳答案

因为你正在使用inline-block,你需要使用vertical-align因为默认是baseline:

神奇的 CSS:

vertical-align: middle;

以上将修复它:

div,
button {
width: 4em;
height: 4em;
background-color: red;
padding: 0;
border: 0;
margin: 1em;
font-size: 1em;
font-family: Arial;
vertical-align: middle;
}

div {
text-align: center;
display: inline-block;
cursor: default;
box-sizing: border-box;
}
<div>text</div>
<button>text</button>

为了使 div 中的文本居中,您需要使用 line-heightheight分区

神奇的 CSS:

line-height: 4em;

div,
button {
width: 4em;
height: 4em;
background-color: red;
padding: 0;
border: 0;
margin: 1em;
font-size: 1em;
font-family: Arial;
vertical-align: middle;
line-height: 4em;
}

div {
text-align: center;
display: inline-block;
cursor: default;
box-sizing: border-box;
}
<div>text</div>
<button>text</button>

关于html - 哪个魔术 CSS 导致 <button> 和 <div> 之间的 text-vertical-align 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39957592/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com