gpt4 book ai didi

css - 在将 div 与文本 block 垂直居中对齐时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-04 10:46:00 25 4
gpt4 key购买 nike

https://jsfiddle.net/n00q5wdn/

请引用 fiddle 的输出加上我正在链接图像以便更清楚地理解问题。

'image'

我只想让“hgroup”垂直居中。

HTML:

<article id="full-height">
<div class="hgroup">
<h1>Exotic Designs</h1>
<h2>Best Quality</h2>
</div>
</article>

SCSS:

#full-height {
background-color: red;
min-height: 600px;
}

.hgroup {
h1 {
color: white;
font-size: 5em;
font-weight: 800;
line-height: 0.8em;
text-shadow: black 0 0 20px;
text-align: center;
}
h2 {
display: block;
color: white;
width: 60%;
max-width: 200px;
margin: 0 auto;
text-align: center;
border: 1px solid white;
margin-top: 15px;
padding: 10px;
background: rgba(0, 0, 0, 0.5);
font-size: 1.3em;
}
}

最佳答案

最适合解决这类问题的是 flexbox,它使用专为这些情况创建的 Box Alignment 规范。

如果将 #full-height 元素设置为显示为 flex 行容器,则可以使用 align-items(垂直)和 justify-content(水平)。

#full-height {
display: flex;
align-items: center;
justify-content: center;
}

参见 forked fiddle here .

这将适用于大多数现代浏览器,如果您通过 Autoprefixer 之类的东西运行它,您也可以让它在一些稍旧的浏览器(IE10、旧版 Safari 等)中运行。 IE9 和其他旧版浏览器不支持 flexbox,因此我建议使用具有固定边距的 .hgroup 元素或仅顶部对齐等作为后备方案。如果您可以使用固定的显式高度关于容器,还有另一个更棘手和复杂的解决方案:

我看到您已经尝试使用 inline-blockvertical-align 来尝试使用 middle 关键字进行垂直居中。仅当您可以在 #full-height 容器上设置明确的高度并使用“ghost”元素强制行高计算覆盖框时,这才会起作用,例如:

#full-height {
height: 600px;
text-align: center; /* horizontal centering */
}
/**
* "ghost element", to force the calculation of the
* middle keyword to equal the vertical middle of
* the box.
*/
#full-height:before {
content: '';
display: inline-block;
vertical-align: middle;
height: 100%;
/* offset the whitespace generated by inline-block.
May vary with font-size. */
margin: -.25em;
}

.hgroup {
display: inline-block;
vertical-align: middle;
}

参见 jsbin example for this solution here .

关于css - 在将 div 与文本 block 垂直居中对齐时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35390894/

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