gpt4 book ai didi

html - 如何垂直对齐和水平对齐div?

转载 作者:行者123 更新时间:2023-11-28 03:02:19 25 4
gpt4 key购买 nike

我有一个视频。我有一组文本,我想像这样在视频顶部垂直和水平居中。 https://imgur.com/a/zfldQ

我也不想使用 transform: translate 方法,因为我想支持 IE8。

https://codepen.io/anon/pen/OjKxxj

<section class="container">

<!-- Video -->
<video src="https://static.videezy.com/system/resources/previews/000/000/108/original/Hiking.mp4"></video>


<!-- Need to center this div -->
<div class="center-group">
<h1>Need to center this</h1>
<h2>Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello</h2>
<a>Button</a>
</div>


</section>

* {
margin: 0;
padding: 0;
}

html, body, .container {
height: 100%;
}

video {
height: 100%;
width: 100%;
object-fit: cover;
}

.center-group {
position: absolute;
width: 500px;
top: 0;
background: orange;
}

最佳答案

您可以使用显示:

  • flex (现在的浏览器)

* {
margin: 0;
padding: 0;
}

html,
body,
.container {
height: 100%;
display: flex;/* update*/
align-items: center;/* update*/
justify-content: center;/* update*/
}

video {
position: absolute;/* update*/
top: 0;/* update*/
left: 0;/* update*/
height: 100%;
width: 100%;
object-fit: cover;
}

.center-group {
position: relative;/* update*/
width: 500px;
/*top: 0; update not needed */
background: orange;
}
<section class="container">

<!-- Video -->
<video autoplay src="https://static.videezy.com/system/resources/previews/000/000/108/original/Hiking.mp4"></video>


<!-- Need to center this div -->
<div class="center-group">
<h1>Need to center this</h1>
<h2>Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello</h2>
<a>Button</a>
</div>


</section>

  • 表格/表格单元格(现在和旧版浏览器)

* {
margin: 0;
padding: 0;
}

html {
height: 100%;
/*update*/
display: table;
width: 100%;
}

body {
display: table-row;
}

.container {
display: table-cell;
vertical-align: middle;
text-align: center;
}

.center-group {
display: inline-block;
text-align: left;
position: relative;
/* end update*/
width: 500px;
background: orange;
}

video {
/*update*/
position: absolute;
top: 0;
left: 0;
/* end update*/
height: 100%;
width: 100%;
object-fit: cover;
}
<section class="container">

<!-- Video -->
<video autoplay src="https://static.videezy.com/system/resources/previews/000/000/108/original/Hiking.mp4"></video>


<!-- Need to center this div -->
<div class="center-group">
<h1>Need to center this</h1>
<h2>Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello</h2>
<a>Button</a>
</div>


</section>

关于html - 如何垂直对齐和水平对齐div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46135195/

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