如何集中这段代码?

时间:2016-05-04 18:05:29

标签: html css center centering

请帮我将下面的代码集中在一起,告诉我你是怎么做到的:

div.img {
    margin: 5px;
    border: 1px solid #ccc;
    float: left;
    width: 180px;
}

div.iframe:hover {
    border: 1px solid #777;
}

div.img iframe {
    width: 100%;
    height: auto;
}

div.desc {
    padding: 15px;
    text-align: center;
}

https://jsfiddle.net/zuntcod0/

2 个答案:

答案 0 :(得分:2)

如果您想要轻松地将这些元素水平居中,您可以考虑使用最外层的<div>元素,为其定义明确的宽度,并使用margin: 0 auto将其整体放在页面中:

<div id='wrapper'>
     <!-- Your Content Here -->
</div>

以及:

#wrapper { 
     width: 800px;
     margin: 0 auto;
}

示例

你可以see a working example of this in action here以及下面的输出结果:

enter image description here

答案 1 :(得分:1)

如果您想要将视频居中,则必须使用text-align: center;,但这不适用于浮动元素。移除视频div上的float: left;并将其替换为display: inline-block。它看起来像这样:

(新小提琴:https://jsfiddle.net/zuntcod0/2/

&#13;
&#13;
div.img {
    margin: 5px;
    border: 1px solid #ccc;
    display: inline-block;
    width: 180px;
}

div.iframe:hover {
    border: 1px solid #777;
}

div.img iframe {
    width: 100%;
    height: auto;
}

div.desc {
    padding: 15px;
    text-align: center;
}
</style>
&#13;
<div style="text-align: center">

<div class="img">
  <a target="_blank" href="fjords.jpg">
    <iframe width="560" height="315" src="https://www.youtube.com/embed/cw7cOOQt5KM" frameborder="0" allowfullscreen></iframe>
  </a>
  <div class="desc">Add a description of the image here</div>
</div>
<div class="img">
  <a target="_blank" href="fjords.jpg">
    <iframe width="560" height="315" src="https://www.youtube.com/embed/cw7cOOQt5KM" frameborder="0" allowfullscreen></iframe>
  </a>
  <div class="desc">Add a description of the image here</div>
</div>
<div class="img">
  <a target="_blank" href="fjords.jpg">
    <iframe width="560" height="315" src="https://www.youtube.com/embed/cw7cOOQt5KM" frameborder="0" allowfullscreen></iframe>
  </a>
  <div class="desc">Add a description of the image here</div>
</div>
<div class="img">
  <a target="_blank" href="fjords.jpg">
    <iframe width="560" height="315" src="https://www.youtube.com/embed/cw7cOOQt5KM" frameborder="0" allowfullscreen></iframe>
  </a>
  <div class="desc">Add a description of the image here</div>
</div>
<div class="img">
  <a target="_blank" href="fjords.jpg">
    <iframe width="560" height="315" src="https://www.youtube.com/embed/cw7cOOQt5KM" frameborder="0" allowfullscreen></iframe>
  </a>
  <div class="desc">Add a description of the image here</div>
</div>

</div>
&#13;
&#13;
&#13;