这是全屏结果:http://jsfiddle.net/anik786/UYkSf/4/embedded/result/
这是 HTML/CSS:http://jsfiddle.net/anik786/UYkSf/4/
这是 HTML:
<div class="gallery_container">
<div class="pic">
<img src="http://petapixel.com/assets/uploads/2012/02/sample1_mini.jpg" />
</div>
<div class="pic">
<img src="http://www.ndaccess.com/Sample/Images/Image1.jpg" />
</div>
<div class="pic">
<img src="http://petapixel.com/assets/uploads/2012/02/sample1_mini.jpg" />
</div>
<div class="pic">
<img src="http://www.ndaccess.com/Sample/Images/Image1.jpg" />
</div>
<div class="pic">
<img src="http://petapixel.com/assets/uploads/2012/02/sample1_mini.jpg" />
</div>
<div class="pic">
<img src="http://www.ndaccess.com/Sample/Images/Image1.jpg" />
</div>
还有 CSS:
* {margin: 0; padding: 0;}
body {background: black;font-family: arial;}
.gallery_container{
/* Insert styles here to make container center on page */
}
.pic {
height: 300px;
width: 300px;
overflow: hidden;
margin: 20px;
border: 10px solid white;
float: left;
}
.pic img{
height: 300px;
width: 300px;
}
问题是,当窗口大小处于特定宽度时,右侧的空间太大(通过调整浏览器大小来尝试全屏结果)。
因此,我尝试将容器居中,以便画廊始终位于屏幕中间。我通常使用:
边距:0 自动;
但是我不能使用它,因为我不知道容器的宽度是多少(因为它取决于窗口大小)。
求助!提前致谢!
最佳答案
居中元素的方法有很多:
margin 方式:
设置宽度或显示:inline-block;你可以使用:
margin-left: auto;
margin-right: auto;
文本对齐方式:
您可以将此添加到父级:
text-align: center;
绝对方式:
position: absolute;
left: 50%;
margin-left: width/2;
或
position: absolute;
left: 50%;
transform: translate(0, -50%);
最好的方法是删除 .pic
上的 float ,而是添加 display: inline-block
。然后在父级上添加 text-align: center;
关于css - 如何在不知道宽度的情况下水平居中 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19388218/