簡體   English   中英

在較小的div內水平對齊div

[英]Horizontally align a div inside a smaller div

我有一個div,我需要在另一個div下顯示,但隨着頁面大小的改變,它會水平對齊。 更改頁面大小會更改第一個div的大小。

我想向.div2下面.div1 ,並居中對齊。

我創造了一個小提琴,以更清楚地展示我在尋找什么。

HTML

<div class="container">
    <img src="http://jamesonstarship.files.wordpress.com/2013/10/beautiful-cat-cats-16096437-1280-800.jpg" />
    <div class="floating-container">
        <div class="floating" style="left:36%;top:26%;width:6%;height:9.5%;">
            <div class="div1">
            </div>
            <div class="div2">
                There is some content here
            </div>
        </div>
        <div class="floating" style="left:55%;top:38%;width:5%;height:8%;">
            <div class="div1">
            </div>
            <div class="div2">
                There is some content here
            </div>
        </div>
    </div>
</div>

CSS

.container {
    width:100%;
    display: inline-block;
    position: relative;
}

.container img {
    width:100%;
}

.floating {
    position:absolute;
}

.div1 {
    border: 3px solid #FFF;
    border-radius: 3px;
    width: 100%;
    height: 100%;
}
.div2 {
    background: rgba(255,255,255,0.4);
    width: 75px;
}

一直試圖解決這個問題幾個小時,所以真的很感激一些幫助!

作為純CSS解決方案,您可以使用%值作為<div>元素的width ,並為第二個div設置一個負margin-left ,如下所示:

.div1 {
    width: 100%;
}

.div2 {
    width: 300%;
    margin-left: -100%; /* <-- (300% - 100%) / 2
                                 |      |
       width of the current div --      -- width of the first div */
}

此外,您需要使用box-sizing: border-box; 為第一個div計算元素的寬度/高度,包括白色邊框:

.div1 {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

這是工作演示

Div具有固定寬度

保留第二個div有兩個選項 (我為演示創建了一個名為.div3的新類) ,它在中心有一個固定的width

1)使用CSS3 calc()函數計算左邊距的正確值。

.div3 {
    width: 150px;
    margin-left: calc((100% - 150px) / 2); /* <-- -1 * (150px - 100%) / 2 */
}

更新的演示

2)使用CSS3 translateX()變換函數,負值百分比值為-50%而元素位於left: 50%;

.div3 {
    width: 150px;
    position: relative;
    left: 50%;
    transform: translateX(-50%);
}

更新的演示

你希望文本div(div2)在白框(div1)下面居中,並且從我的代碼中我可以理解,你希望div2固定75px大小和div1變量,百分比位置和大小? CSS不是我的強項,但我不認為你能用純CSS做到這一點。 所以我只能建議這樣的jQuery解決方案:

$(".div2").each(function(){
$(this).css('margin-left',(($(this).prev().width()-$(this).width())/2));
});

還要確保在窗口上添加此功能,如下所示:

$(window).on('resize', function(){
$(".div2").each(function(){
$(this).css('margin-left',(($(this).prev().width()-$(this).width())/2));
});
});

是一個演示

如果有人知道如何使用純CSS做到這一點,或者有更好的解決方案,請填寫免費分享。

暫無
暫無

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

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