簡體   English   中英

在div中垂直居中並在右側居中

[英]Center image vertically and to the right in a div

我想將ID為“ image”的圖像居中放置在右側和垂直方向。

使用PHP創建我的DIV,如下所示:

echo 
    "<div class=\"first\">
    <div id=\"second\"><label id=\"second_div_label\"></label>
    <img id=\"image\" src=\"images/my_image.png\"/>
    </div>
    <div id=\"third\"></div>
    </div>";

我的CSS代碼是

.first {
    display: block;
    width: 50%;
    height: auto;
    margin: 0px auto;
    margin-bottom: 15px;
}

#second {
    margin-top: 5%;
    background-color: #3f51b5;
    border-radius: 5px;
    font-weight: bold;
    padding: 20px;
}

#third {
    margin-top: 15px;
    border-radius: 5px;
    padding: 20px;
}   

#image {
    width: 35px;
    height: 35px;
    float: right;
}

多虧了float:right ,圖片位於DIV的右側,但它不是垂直居中,並且頁margin-bottom不起作用。 我該如何解決?

您可以使用position:absolute技巧,然后使用SebastianEkström的出色代碼將其設置在右側並垂直居中。 請注意,要使其正常工作,父標記必須具有position:relative

由於該元素是絕對定位的,因此不需要float:right

例:

 .first { display: block; width: 50%; height: auto; margin: 0px auto; margin-bottom: 15px; } #second { margin-top: 5%; background-color: #3f51b5; border-radius: 5px; font-weight: bold; padding: 20px; position:relative; } #third { margin-top: 15px; border-radius: 5px; padding: 20px; } #image { width: 35px; height: 35px; position:absolute; top: 50%; right:10px; transform: translateY(-50%); } 
 <div class="first"> <div id="second"> <label id="second_div_label"></label> <img id="image" src="http://i.stack.imgur.com/CE5lz.png"/> </div> <div id="third"></div> </div> 

PS,您可能要為transform屬性添加供應商前綴

  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);

Aziz的CSS應該可以在現代瀏覽器中使用。 但是,為了獲得輕松的跨瀏覽器體驗,並且如果您不介意使用javascript,則可以考慮使用jQuery,如下所示:

<script>
    $(document).ready(function(){
        $('#image').position({
            my: 'right center',
            at: 'right center',
            of: '.first'    //or whichever container you wish to use
        });
    });
</script>

然后,您將不需要在CSS中實現浮動以及相對和絕對定位。

#image {
        width:35px;
        height:35px;
        float:right;
        position: relative;
        top: 50%;
        -webkit-transform: translateY(-50%);
        -ms-transform: translateY(-50%);
        transform: translateY(-50%);
  }

請將此樣式添加到圖像。 還要注意一件事,您必須定義父div(id = second)的高度,並且其值大於圖像高度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM