gpt4 book ai didi

html - 固定 div 中具有 block 兄弟的未知大小的垂直和水平居中元素

转载 作者:行者123 更新时间:2023-11-28 16:34:01 24 4
gpt4 key购买 nike

我有一个固定在屏幕左侧的边栏

我在侧边栏顶部的段落标记中有当前时间。此元素的宽度用于设置侧边栏的宽度。

我正在努力的是向侧边栏添加另一个段落,该段落在侧边栏中水平和垂直居中。

我看过许多其他居中元素的示例,但似乎无法理解。非常感谢您的帮助。

基本结构:

<div id="left">
<p id="time">
12:03<span>45</span>
</p>
<p id="currentWeather">
<!-- I've replaced this <i> with an <img> to avoid loading the font in the fiddle -->
<i class="wi wi-day-sunny"></i>
<img src="http://findicons.com/files/icons/2603/weezle/256/weezle_sun.png">
<span>32</span>
</p>
</div>

fiddle :https://jsfiddle.net/w5m7qd6u/1/

最佳答案

也许这就是您要找的...

height: 100vh 的组合在父元素上,将顶部元素设置为 position: absolute因此不会垂直定位,并向 <p> 添加样式你将垂直居中:

#currentWeather {
top: calc(50%);
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
}

下面是完整的代码和片段:(为了清楚起见,请查看完整页面)

我注释掉了字体大小,以便在使用较小的窗口时更容易使用,但这不应该影响它。

html,
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
font-family: "Roboto", Helvetica, sans-serif;
}

#left {
position: fixed;
z-index: 1;
top: 0;
left: 0;
height: 100vh;
box-sizing: border-box;
padding: 24px;
background-color: rgba(0, 0, 0, 0.7);
color: white;
text-align: center;
}

#time {
position: absolute;
width: 100%;
left: 0;
padding: 0;
margin: 0;
/* font-size: 90pt; */
}

#time > span {
margin-left: 6px;
/* font-size: 24pt; */
}

#currentWeather {
position: relative;
left: 0;
/* font-size: 84pt; */
margin: auto;
top: calc(50%);
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
}

#currentWeather > span {
display: block;
/* font-size: 40pt; */
}


/* this is just a placeholder. real image is dynamic and won't have set height */

img {
width: 124px;
height: auto;
}
<div id="left">
<p id="time">
12:03<span>45</span>
</p>
<p id="currentWeather">
<!-- <i class="wi wi-{{currentConditions}}"></i> -->
<!-- have used image for placeholder to avoid uploading font -->
<img src="http://findicons.com/files/icons/2603/weezle/256/weezle_sun.png"><span>32</span>
</p>
</div>

关于html - 固定 div 中具有 block 兄弟的未知大小的垂直和水平居中元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34868943/

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