gpt4 book ai didi

html - 固定位置 div 内的 CSS 垂直对齐

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

我有一个标题:固定位置。

这是CSS:

#header{
position:fixed;
height: 6em;
display:block;
width: 100%;
background: rgba(255, 255, 255, 1);
z-index:9;
text-align:center;
color: #000000;
}

在里面,我想将文本居中和垂直居中。到目前为止,这是我所拥有的,但它不起作用。所有在线示例都显示了作为容器的绝对位置,但它不适用于固定位置。

HTML:

<div id="header">
<div id="bandname">Bewolf Photography</div>
<div id="insta"><img src="imgs/insta.png" width="40" alt="tablets" /></div>
<div id="bandname">Bewolf Photography</div>
</div>

文本和图像的 CSS:

#bandname
{
display: inline-block;
font-size: 2.8em;
padding: 0px 0px 0 0;
vertical-align: middle;
background: rgba(0, 255, 0, 1);
}

#insta {
display: inline-block;
padding: 0px 0px 0px 50px;
vertical-align: middle;
}

我就是想不通那个……

我试过用

   line-height:  6em;  

帮助将不胜感激..谢谢但这也不起作用。

最佳答案

使用伪元素垂直居中技巧。

#header:before将内联元素带到中心。 header 的直接子级给出 display: inline-blockvertical-align: middle保持直线。

Read more about pseudo elements here.

这种技术基本上是在其余内容之前添加一个“div”。 (它可以用真正的 <div> 代替,如果你真的需要它在 IE7 和更低版本中工作。[不要打扰!])。它基本上看起来像这样:

<div class="header">
<!-- added by css -->
<div>I am :before and you will all do as I say! To the middle, plebs!</div>
<!-- end css content -->

<div>Yes master!</div>
<div>Anything you say sir!</div>
</div>

工作示例

注意:我删除了图像周围的 div。这似乎是不必要的,但如果需要可以放回去。此外,我只针对 #header 的直接子级使用直接子选择器:> . Here is a huge list of CSS selectors.

#header {
position: fixed;
height: 6em;
display: block;
width: 100%;
background: rgb(0, 255, 255);
/* Fall-back for browsers that don't support rgba */
background: rgba(0, 255, 255, 1);
z-index: 9;
text-align: center;
color: #000000;
top: 0px;
}
#header:before {
content: '';
display: inline-block;
vertical-align: middle;
height: 100%;
}
#header > div,
#header > img {
display: inline-block;
font-size: 2.8em;
padding: 0px 0px 0 0;
vertical-align: middle;
}
<div id="header">
<div id="bandname">Test</div>
<img src="http://www.placehold.it/50" width="40" alt="tablets" />
<div id="bandname">test</div>
</div>

关于html - 固定位置 div 内的 CSS 垂直对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26600931/

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