Attach div to the right of another div

随声附和 提交于 2021-01-02 05:36:06

问题


I have a div which is like a container and inside of it there are 2 images. One image is on the left side of the div and the other is on the right. My container is Bootstrap's container

Both of them are wrapped with a div, and that div's position is fixed.

My problem is that I can't locate the right image to be attached to the right side of the conatiner. I tried the float and the right properties but they not give the expected result.

How can I attach div to the right of another div?


回答1:


https://jsfiddle.net/mqwbcLn8/5/ fixed Nem's code.

HTML:

<div class="container">
    <div class="left-element">
        left
    </div>
    <div class="right-element">
        right
    </div>
</div>

CSS:

.container {
    position: fixed;
    left: 350px;
    padding: 0;
    margin: 0;
    background-color: #ff00ff;
}

.left-element {
    background: green;
    display: inline-block;
    float: left;
}

.right-element {
    background: red;
    display: inline-block;
    float: left;
}

You float both elements, so they are always sticked together. Then you just move the wrapping div and they both keep together. I added pink background so you can see that you don't lose any space with that solution.

The wrapper is just for the position and to keep the other two elements in place. Like this you can position those two elements as you wish, while they always stay together like this.




回答2:


If I'm understanding your problem correctly, you have a large container with fixed position. A left div on the inside of the container that sticks to the inside left, and a right div inside the container that sticks to the inside right?

You can just set the display to inline-block which will force them side by side, and then use left/right to position them within the container:

HTML:

<div class="container">
    <div class="left-element">
        left
    </div>
    <div class="right-element">
        right
    </div>
</div>

Your css would just look like this:

.container {
    width:500px;
    position: fixed;
}

.left-element {
    background: green;
    display: inline-block;
    position: absolute;
    left: 0;
}

.right-element {
    background: red;
    display: inline-block;
    position: absolute;
    right: 0;
}

jsfiddle: https://jsfiddle.net/mqwbcLn8/3/



来源:https://stackoverflow.com/questions/31830089/attach-div-to-the-right-of-another-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!