如何使用 CSS 将一个 div 水平居中放置在一个 div 中?我正在尝试,我让它从左和右居中,但我无法让它从顶部和底部居中。
html {
height:100%;
}
body {
padding:0px;
margin: 0px;
height:100%;
}
#openFrame {
position:fixed;
top:0px;
width:100%;
left:0%;
height:100%;
}
.main {
position: absolute;
width: 80%;
max-height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
#vid {
width:100%;
max-height:100%;
vertical-align: middle;
}
#bottom {
width:100%;
height:69px;
background-color: green;
background-repeat: no-repeat;
background-position: top center;
background-size: contain;
}
最佳答案
将 DIV 垂直居中有点棘手。基本上,您必须将容器的 position
设置为 absolute
并将容器的 position
设置为 relative
。然后将 top
和 left
值设置为 50%,并通过应用负边距减去要居中的元素的宽度/高度的一半。
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
body, html, #container {
height: 100%;
width: 100%;
}
#container {
position: relative;
}
#content {
width: 300px;
height: 300px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -150px;
margin-left: -150px;
background-color: red;
}
</style>
</head>
<body>
<div id="container">
<div id="content"></div>
</div>
</body>
</html>
关于html - CSS 居中 DIV 包含其他 DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30990050/