简体   繁体   中英

Text is shifted when mixing floated and relatively positioned elements

I'm looking to solve with CSS a problem that I found far trickier than expected.

Here is the smallest (valid) html fragment I was able to build that expose the issue:

<!doctype html>
<html>
    <head>
        <title></title>
        <style>
            body, div {margin: 0; color: white;}
        </style>
    </head>
    <body>
        <div style="float: left; background-color: #000; width: 200px; height: 200px;"></div>
        <div style="background-color: #333; position: relative; left: 200px; height: 200px;">This is a test !</div>
    </body>
</html>

Does someone know how to prevent the text "This is a test !" To be shifted to the right by the floated element ?

I'm guessing that the floated element is the culprit since when I remove it the text is at the right place. Also changing the order of the divs doesn't yield the expected result.

Thank you !

Replace left: 200px; on your right side div with margin-left: 200px;

Fiddle to prove here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM