Align a div horizontally inside a smaller div

I have a div that I need to display under another div, but with horizontal alignment as the page resizes. Resizing the page resizes the first div.

I would like to place .div2under .div1and center.

I created a violin to show more clearly what I'm looking for.

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;
}

We tried to understand this for a couple of hours, so I would really like some help!

+4
source share
2 answers

CSS, % width <div> margin-left div :

.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%);
}

.

+3

, 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 , , , .

0

Source: https://habr.com/ru/post/1527133/


All Articles