简体   繁体   English

在中心/左边对齐div

[英]align divs on center/left

Can somebody please help me with this piece of code? 有人可以帮我解决这段代码吗?

HTML: HTML:

<div id="container">
  <div class="block"> </div>
  <div class="block"> </div>
  <div class="block"> </div>
  <div class="block"> </div>
</div>

CSS: CSS:

#container {
  margin:auto;
  text-align:center;
  padding:10%;
}
.block {
  width:240px;
  height:300px;
  background: red;
  display:inline-block;
}

jsfiddle 的jsfiddle

I want it so that the whole container aligned in the middle but when there is an extra block at the bottom, it should go to the left. 我想要它,以便整个容器在中间对齐,但是当底部有一个额外的块时,它应该向左移动。 Is that possible? 那可能吗?

This works: 这有效:

HTML: HTML:

#container {
  margin:auto;
  text-align:center;
  width:70px;
  overflow:hidden;}

CSS: CSS:

.block {
  width:24px;
  height:30px;
  float:left;
  margin:5px 5px;
  background: red;}

See the jsfiddle here. 在这里查看jsfiddle I changed the sizes so that it's easier to see but you can readjust them according to your site. 我更改了尺寸,以便更容易看到,但您可以根据您的网站重新调整它们。 Basically, you need overflow:hidden; 基本上,你需要overflow:hidden; and set the width of the container so that it can only fit 2 blocks per row so that the next block goes underneath and is aligned to the left. 并设置容器的宽度,使其每行只能容纳2个块,以便下一个块位于下方并与左侧对齐。 Also, remember that ids must be unique in your page; 另外,请记住,ID在页面中必须是唯一的; if you need more than one element with the same definition then you must use classes. 如果您需要多个具有相同定义的元素,则必须使用类。

I would use float: left in block id,remove container from css and use class instead of id because id must be used once: 我会在块id中使用float: left ,从css中删除容器并使用class而不是id,因为id必须使用一次:

HTML: HTML:

<div>
    <div class="block"> </div>
    <div class="block"> </div>
    <div class="block"> </div>
    <div class="block"> </div>
</div>

CSS: CSS:

.block {
    width:40%;
    height:300px;
    margin: 5%;
    float: left;
    background: red;
    display:block;
}

Try this plugin for jQuery to help you organize the DIV. 试试这个jQuery插件来帮助你组织DIV。 desGridLayout: http://des.delestesoft.com:8080/?go=8 desGridLayout: http ://des.delestesoft.com:8080 /?go = 8

I solved my own problem with @media queries : 我用@media查询解决了我自己的问题:

@media screen and (max-width: 840px) {
.portfolio_container {
    width:512px;
    }
}

@media screen and (max-width: 580px) {
.portfolio_container {
    width:255px;
    }
}

I know media queries are not compatible with older browser versions! 我知道媒体查询与旧浏览器版本不兼容! but at least it is supported by all most recent versions! 但至少它受到所有最新版本的支持!

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

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