简体   繁体   English

具有背景颜色的元素垂直对齐父级中间

[英]Element with background color vertical align middle of the parent

I am trying to achieve this "stupid" thing, but I can't find a solution. 我正在尝试实现这一“愚蠢”的目标,但找不到解决方案。 I have a certain number of images one above the other, I would try to put background-color which is aligned vertically in the middle of the first and last image. 我的上面有一定数量的图像,我会尝试将背景色垂直放置在第一张和最后一张图像的中间。 more difficult to explain than to understand, I made an image explanatory so I think it is more easy to understand 比解释更难解释,我对图像做了解释,所以我认为它更容易理解 在此处输入图片说明

I tried to make a codepen, but without success http://codepen.io/mp1985/pen/BoEMPN 我试图制作一个Codepen,但未成功http://codepen.io/mp1985/pen/BoEMPN

.bg {
  background: red;
  top: 25%;
  position: absolute;
  width: 100%;
  height: 100%;
  bottom:0;
  left: 0;
  right: 0;
  z-index: 100;
  backgrund-position: center center;
  z-index: 1;
}

do you have any advice or suggestion? 您有什么建议或建议吗?

Well, I'm not sure I've understood but how you started isn't correct: you want your images at the center of the page, right? 好吧,我不确定我是否了解,但是您的开始方式不正确:您希望图像位于页面中心,对吗? Well, to do that they must be positionated with 好吧,要做到这一点,他们必须与

position: relative;
left:50%;

Then, you created a div as a background. 然后,您创建了一个div作为背景。 There you can choose: you can create a dinamic background with JS, or add only a certain number of images with a certain known height. 您可以在其中选择:您可以使用JS创建动态背景,或仅添加一定数量的具有已知高度的图像。 I guess you are creating a static page, so set the div with 我想您正在创建静态页面,因此将div设置为

position: relative;
min-height: 900px; //(imgNum-1)*imgHeight 
top: 150px; //imgHeight/2 

and with what you have already set. 以及您已经设置的内容。 If you have width problems, min-width and max-width are useful attributes. 如果您遇到宽度问题,则最小宽度和最大宽度是有用的属性。

In my mind it works. 在我看来,它有效。 Please comment for issues and rate positive if useful 请对问题发表评论,并在有用时打分

You can't set the parent's height according to an absolutely positioned element. 您不能根据绝对定位的元素设置父母的身高。 So you have to use fixed lengths rather than percentages. 因此,您必须使用固定长度而不是百分比。

.container {
  height: 900px; // img-height * 4
}

Then, for the background color to align to the center of the first image, add this: 然后,为了使背景颜色与第一张图像的中心对齐,请添加以下内容:

.bg {
  top: 150px; // img-height / 2
}

As for horizontally centering the imgs, use 至于img的水平居中,请使用

.box-images {
  left: 50%;
  margin-left: -300px; // img-width / 2
}

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

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