【问题标题】:Centering relative div to background image将相对 div 居中到背景图像
【发布时间】:2019-09-18 12:29:49
【问题描述】:
我想知道如何让 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;
}
谢谢。 :)
【问题讨论】:
标签:
html
css
image
center
【解决方案1】:
你没有提到这是否需要纯 CSS,但如果你能够使用 Bootstrap 4,那么你可以这样做:
<div class="d-flex justify-content-center align-items-center">
<div>
Hello world
</div>
</div>
【解决方案2】:
您可以在 css 中使用“display: flex”、“justify-content: center”和“align-items: center”属性来做到这一点。这是一个小提琴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(在本例中为“背景”)中使用这些属性来使其内容居中 - 子 div(“覆盖框”)。我还在子项中添加了“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;
}