Search code examples
htmlcssposition

how to make div tag appear directly to the right of the preceding div tag


I have the following code in HTML:

<!DOCTYPE html>
<html>
<head>
    <title>test</title>
    <style>
        .left {
            width: 30px;
            background-color: green;
        }
        .right {
            background-color: red;
            width: 30px;
        }
    </style>
</head>
<body>
    <div class="left">Text</div>
    <div class="right">Text</div>
</body>
</html>

The red div appears directly underneath the green div, but I want to make it so that the red div is directly to the right of the green div - how should I do this? Adding a float: right css property does not work as it goes to the other side of the page.


Solution

  • .left {
        float: left;
        width: 30px;
        background-color: green;
    }
    .right {
        float: right;
        background-color: red;
        width: 30px;
    }
        <div class="left">Text</div>
        <div class="right">Text</div>
        

    You have to use floats to achieve this

    <!DOCTYPE html>
    <html>
    <head>
        <title>test</title>
        <style>
            .left {
                float: left;
                width: 30px;
                background-color: green;
            }
            .right {
                float: right;
                background-color: red;
                width: 30px;
            }
        </style>
    </head>
    <body>
        <div class="left">Text</div>
        <div class="right">Text</div>
    </body>
    </html>