【问题标题】:centering only works with fixed positioning, not absolute居中仅适用于固定定位,而不是绝对定位
【发布时间】:2016-04-20 01:14:54
【问题描述】:

我有一个 div,我试图在其中使图像居中。如果位置设置为固定,它会完美居中,但是当位置设置为绝对时,图像向右太多像素。

我不能将位置设置为固定,因为当用户单击某些内容时,此 div 会从顶部滚动,所以直到那一刻我才能看到它。我以前从来没有遇到过这个问题。谁能告诉我怎么了?

html:

<div class="header">
    <img class="logo" src="img/navbar_title.jpg"/>
    <img class="tab" src="img/mid_tab.png" /><!-- image to be centered -->
    <div class="header_social">
        <img src="img/button_pg.jpg" />
        <img src="img/button_facebook.jpg" />
        <img src="img/button_twitter.jpg" />
    </div>
</div>

css:

.header
{
position:fixed;
top:-100px;
width:100%;
height:30px;
padding:10px;
background-color:black;
color: white;
z-index:10;
margin-top:0px;
box-shadow: gray 3px 0px 10px;
}

    .header .logo
    {
        position: absolute;
        top: 10px;
        z-index: 4;
        left: 20px;
    }
    .header .tab { /* not working right */
        position: absolute;
        top: 0;
        z-index: 4;
        left: 50%;
        transform: translateX(-50%);
        -moz-transform: translateX(-50%);
        -ms-transform: translateX(-50%);
        -webkit-transform: translateX(-50%);
    }

    .header h1
    {
    font-family: Helvetica, sans-serif;
    font-weight: bold;
    font-size:14pt;
    display:inline-block;
    line-height:30px;
    float:left;
    margin-top: 0;
    margin-left: 20px;
    letter-spacing: .05em;
    color: #303030;
    }

    .header .header_social
    {
    float:right;
    height:30px;
    line-height:30px;
    width:150px;
    }

【问题讨论】:

    标签: css position centering


    【解决方案1】:

    这是由于盒子尺寸。当您定位固定时,它是相对于整个屏幕,周期。当您定位绝对时,它相对于最近的非静态位置父级。在您的情况下,这就是您的 div.header。你的 div.header 有一个 padding 和一个 100% 的宽度,所以它实际上是 100% + 20。在你的 div.header 上设置 box-sizing:border-box 并且你的图像会向左移动几个像素。 :)

    【讨论】:

      猜你喜欢
      • 2011-03-10
      • 1970-01-01
      • 1970-01-01
      • 2011-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多