使事物和布局元素相互关联 - 如何正确地做到这一点

时间:2015-12-17 09:09:42

标签: html css

我需要在我的网页上获得以下布局:

enter image description here

所有元素都有固定的高度(图片显示在占位符,YouTube播放器 - 640x390),所有这些元素都应放在文档的中心。

我能想到的最佳解决方案如下:

CSS

.center-both {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  -webkit-transform: translate(-50%,-50%);
  -webkit-filter: blur(0);
}

 #logo {
  display: block;
  margin: auto;
}

 #player {
  margin-top: 30px;
  width: 640px;
  max-width: 640px;
  height: 390px;
  max-height: 390px;
}

#copy {
  margin-bottom: 131px;
}

 #next {
  margin-bottom: 131px;
}

HTML

<div class="center-both">
  <img id="logo" src="http://placehold.it/246x105">
  <img id="copy" src="http://placehold.it/128x128">
  <iframe id="player" frameborder="0" allowfullscreen="1" title="YouTube video player" width="640" height="390" src="https://www.youtube.com/embed/?enablejsapi=1&amp;origin=http%3A%2F%2F127.0.0.1%3A3000"></iframe>
  <img id="next" src="http://placehold.it/128x128">
</div>

(JSFiddle给我垃圾结果btw - https://jsfiddle.net/aadzfkmr/

所以:

  • center-both类应该用于文档中所有元素的垂直和水平居中
  • #logo应将display: blockmargin: auto个样式放在YouTube播放器的顶部,而不是左对齐。
  • margin-bottom: 131px是一个丑陋的黑客,我现在用它来垂直对齐左右图像(玩家高度的390px /图像的高度为2到128px / 2 = 131px)
  • #player应具有固定的高度和宽度,因为它会通过JS动态转换为iframe元素中的div

它可以工作,但是当所有元素占据正确位置之前页面加载时,我会有一个难看的闪烁。

实际上,尽管上面有徽标,但将YouTube播放器置于文档的中心会更好(它可以放置得高一些)。

达到我想要的最佳方式是什么?

3 个答案:

答案 0 :(得分:2)

如果您不担心响应式设计已完成,请转到以下解决方案!

* {
  box-sizing: border-box;
}
.w-896 {
  width: 896px;
}
.text-center {
  text-align: center;
}
.center-both {
  display: table;
  table-layout: fixed;
  margin-top: 30px;
}
.child {
  display: table-cell;
  vertical-align: middle
}
.center-block {
  display: block;
  margin: 0 auto;
}
.w-128 {
  width: 128px;
}
w-frame {
  width: 640px
}
<div class="w-896 text-center">
  <img id="logo" src="http://placehold.it/246x105" class="center-block">
</div>
<div class="center-both w-896">
  <div class="child w-128">
    <img id="copy" src="http://placehold.it/128x128">
  </div>
  <div class="child w-frame">
    <iframe id="player" frameborder="0" allowfullscreen="1" title="YouTube video player" width="640" height="390" src="https://www.youtube.com/embed/?enablejsapi=1&amp;origin=http%3A%2F%2F127.0.0.1%3A3000"></iframe>
  </div>
  <div class="child w-128">
    <img id="next" src="http://placehold.it/128x128">
  </div>

</div>

答案 1 :(得分:1)

试试这个:

#player {
  margin-top: 30px;
  width: 640px;
  max-width: 640px;
  height: 390px;
  max-height: 390px;
}

#copy {
  margin-bottom: 131px;
}

 #next {
  margin-bottom: 131px;
}
.center-both {
  display:block;
  text-align:center;
}
#logo {
  display:block;
  margin:0 auto;
  width:246px;
  height:105px;
}

答案 2 :(得分:1)

请试一试。

#logo {
  margin-bottom: 25px;
}
#player {
  width: 640px;
  height: 390px;
}

请参阅此工作jsfiddle