简体   繁体   English

(大)div在较小的div内水平居中。 纯CSS解决方案可能吗?

[英](Large) div horizontally centered inside smaller div. Pure CSS solution possible?

I would like to have the "Shadow" div centered horizontally inside "Wrapper". 我想让“Shadow”div在“Wrapper”中水平居中。 Since the specific width of the "Wrapper" is unknown due to width: 100%, it is also unknown whether the "Shadow" div is larger or smaller than its container. 由于宽度:100%,“Wrapper”的特定宽度未知,因此“Shadow”div是否大于或小于其容器也是未知的。

Is this even possible? 这甚至可能吗? I could not think of any solution. 我想不出任何解决方案。 Auto margin doesnt work. 自动保证金不起作用。 CSS&HTML only please . 请使用CSS和HTML

Code for demonstration: 示范代码:

HTML: HTML:

<div class="Wrapper">
  <div class="Shadow">some content</div>
  <div class="Content">some content</div>
</div>

CSS: CSS:

.Wrapper{ width: 100%; height: 100%; position: relative; background: url(path) top center no-repeat; max-width: 1520px; max-height: 1050px; overflow: hidden; }
.Shadow{ width: 1520px; height: 1050px; }
.Content{ position:absolute; top: 20px; left: 20px; width: 800px; height: 500px; }

You could try something like this: DEMO 你可以试试这样的东西: DEMO

where you use margin-left: 50% to move the child to the center of the wrapper and then using left to move the child left for half of its width. 您使用margin-left: 50%将子项移动到包装器的中心,然后使用left将子项向左移动一半的宽度。

relevant lines of CSS from my example: 我的例子中相关的CSS行:

.wrapper {
    position:relative;
    /* other properties */
}
.shadow {
    position: absolute;
    margin-left: 50%;
    width: 400px;
    left: -200px;
    /* other properties */
}

Or alternatively: 或者:

you coul use transform:translate(-760px); 你可以使用transform:translate(-760px); in place of left - then you don't need to position the shadow element absolutely, see this DEMO . 代替left - 那么你不需要绝对定位阴影元素,请参阅此演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM