[英]How to Vertically Position DIV Elements in CSS
我在 CSS 中定位我的内容时遇到问题。 我想把我的内容和垂直 position 它。 我曾尝试使用 flexbox 但它没有用。 我知道 flexbox 是什么以及它的属性,但它对我不起作用。 这是 CSS 和 HTML 代码。
HTML:
<div class="main-div">
<div class="container-1">
<h2>What is Your Age In Days?</h2>
<div class="flex-box-container-1">
<div>
<button class="btn btn-primary" onclick="ageInDays()">Click Me!</button>
</div>
<div>
<button class="btn btn-danger" onclick="reset()">Try Again</button>
</div>
</div>
<div class="flex-box-container-1">
<div id="flex-box-result"></div>
</div>
</div>
<div class="container-2">
<h2>Generator</h2>
<button class="btn btn-success" id="picture-generator" onclick=pictureGenerator()>GENERATE</button>
<div class="flex-box-container-2" id="picture-gen">
</div>
</div>
</div>
CSS:
body {
background-image: url(Background.jpeg)
}
.container-1, .container-2 {
border: 1px solid;
margin: 0 auto;
text-align: center;
width: 75%;
}
.flex-box-container-1, .flex-box-container-2 {
display: flex;
padding: 10px;
border: 1px solid black;
flex-wrap: wrap;
flex-direction: row;
justify-content: space-around;
}
.flex-box-container-1 div {
padding: 10px;
align-items: center;
display: flex;
}
#flex-box-result {
font-size: 32px;
font-weight: bold;
}
#yikes {
font-size: 32px;
font-weight: bold;
Animation-name: example;
Animation-duration: 0.5s;
animation-iteration-count: infinite;;
}
@keyframes example {
10% {color: red;}
15% {color: yellow;}
20% {color: blue;}
30% {color: green;}
40% {color: lightsalmon;}
50% {color: lightsteelblue}
60% {color: steelblue}
70% {color: ivory}
80% {color: purple}
90% {color: pink}
100% {color: magenta;}
}
.flex-box-container-2 img {
box-shadow: -12px 11px 28px 6px rgba(0,0,0,0.69);
margin: 10px;
}
所以,我必须垂直对齐容器 1 和 2。我尝试使用Justify Content和Align Items来做到这一点,但它没有用。 我感谢每一点帮助。
你可以使用flex-direction: column
来垂直 position 吧。
如果 Flex 不适合您,据我所知,还有另外两种方法可以做到。
第一个是使用display: table; width: 100%;
display: table; width: 100%;
在父元素上,并display: table-cell; vertical-align: middle;
display: table-cell; vertical-align: middle;
在要垂直对齐的孩子身上。
第二个涉及使用position: relative
对于父元素,和position: absolute; top: 50%; transform: translateY(-50%);
position: absolute; top: 50%; transform: translateY(-50%);
在孩子们身上。
如果您想将container-1和container-2居中,一个在另一个之上,您必须创建另一个div来包装这两个。 在这种情况下,这将是您的子元素。
如果您希望两个容器彼此相邻,请使用引导程序的网格系统为它们提供适当的col类,并将这两个容器视为子容器。
在上述两种情况下,您的父元素都应该是.main-div 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.