我想知道如何让Div Box居中并相对于背景图像,以便保持响应? div框应该在白框内。例如。 http://sendvid.com/t4d85cqe
body{
font-family: 'Roboto Mono', monospace;
background-image: url("assets/handheld_bg_white.png");
background-size: cover;
background-repeat: no-repeat;
}
.overlay-box {
position:absolute;
top:50%;
left:50%;
transform:translate(-50%, -50%);
z-index: 1000;
}
谢谢。 :)
您没有提到这是否需要纯CSS,但如果您能够使用Bootstrap 4,那么您可以按如下方式执行:
<div class="d-flex justify-content-center align-items-center">
<div>
Hello world
</div>
</div>
我会查看flexbox CSS,这对于让事物垂直和水平居中以及其他有用位的音调非常有用。
Flexbox适用于建筑设计,其中定位非常重要,并有助于保持一致性。
This tutorial is a good starting point。
查找下面和一个非常相似的示例示例,以便您可以将其应用于您自己的示例。 (它首先垂直居中,然后水平居中于back-ground
的中心)。
.back-ground {
height: 150px;
width: 150px;
display: flex;
background: #FF0000;
flex-direction: column;
justify-content: center;
}
.box {
display: flex;
justify-content: center;
}
.text {
color: #FFFFFF;
}
<div class="back-ground">
<div class="box">
<span class="text">x</span>
</div>
</div>
您可以使用“display:flex”,“justify-content:center”和“align-items:center”属性在css中执行此操作。这是一个小提琴https://jsfiddle.net/yr510dcb/,下面是一些代码示例:
body{
font-family: 'Roboto Mono', monospace;
background-image: url("assets/handheld_bg_white.png");
background-size: cover;
background-repeat: no-repeat;
}
.background {
display: flex; /* establish flex container */
justify-content: center; /* center items vertically */
align-items: center; /* center items horizontally */
height: 50vw;
width: 80vw;
padding: 20px;
margin: 20px;
background-color: blue;
position:relative;
z-index: 100;
}
.overlay-box {
display: flex; /* establish flex container in case its content needs to be centered */
justify-content: center; /* center items vertically in case its content needs to be centered */
align-items: center; /* center items horizontally in case its content needs to be centered */
margin: 0 auto;
height: 25vw;
width: 25vw;
background-color: white;
position:relative;
z-index: 1000;
position:relative;
}
<div class = "background">
<div class = "overlay-box">
</div>
</div>
您可以在父div(在本例中为“background”)中使用这些属性来居中其内容 - 子div(“overlay-box”)。我也在孩子中添加了“flex”和“center”属性,所以它的内容再次居中,但你可以删除它而不影响“overlay-box”本身的居中。
如果您有背景图像,则可以将图像包装在父div中,例如
<div class = "background">
<img src="/image.png" class="responsive"> /* image location - in this case a local image */
<div class = "overlay-box">
</div>
</div>
并在css中添加一个响应式类,以使其响应和父级的大小:
.responsive {
width: 100%;
height: auto;
}