【问题标题】:How to horizontally centre a div without knowing its width?如何在不知道其宽度的情况下将 div 水平居中?
【发布时间】:2013-10-15 18:14:42
【问题描述】:

这是全屏结果: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 自动;

但是我不能使用它,因为我不知道容器的宽度是多少(因为它取决于窗口大小)。

请帮忙!提前致谢!

【问题讨论】:

    标签: css html screen-size


    【解决方案1】:

    有很多方法可以使元素居中:

    保证金方式:

    具有设置宽度或显示: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 上的浮点数,然后添加 display: inline-block。然后在父节点上添加text-align: center;

    【讨论】:

    • 感谢您这么好的回答
    【解决方案2】:

    您可以使用display: table 将尚未定义给定宽度的项目居中。然后使用margin: 0 auto;

    例如http://jsfiddle.net/LstNS/11/

    div {
        margin: 0 auto;
        display: table;
    }
    

    【讨论】:

      【解决方案3】:

      你也可以使用最大宽度居中

      max-width: 80%;
      margin: 0 auto;
      

      我认为画廊在响应式网站中无论如何都会有 % 宽度。

      【讨论】:

        猜你喜欢
        • 2013-03-03
        • 1970-01-01
        • 2012-04-17
        • 2012-05-04
        • 2011-12-30
        • 2016-08-30
        • 2023-03-02
        • 1970-01-01
        • 2010-12-21
        相关资源
        最近更新 更多