Search code examples
htmlcssalignment

Strange alignment error - CSS


I am trying to float the elements, required and nrequired, to the right of the div #contact with 20px spacing between the elements. This works perfectly for the required elements, but when I insert a nrequired element, the nrequired element aligns itself to the left of the last required element with no regards to the 20px spacing. Please can you tell me what is causing this?

Here is an image to show this strange occurrence, and my code.

#contact #required {
    background-image: url('../img/req_field.png');
    background-repeat: no-repeat;
    width: 441px;
    height: 54px;
    margin-bottom: 20px;
    float: right;
    display: block;
}

#contact #nrequired {
    background-image: url('../img/field.png');
    background-repeat: no-repeat;
    width: 421px;
    height: 54px;
    margin-bottom: 20px;
    float: right;
    display: block;
}

<div id="email">
    <h1>Shoot me an email </h1>
    <h2> (All required fields are marked *)</h2>
    <div id="required"/>
    <div id="required"/>
    <div id="nrequired"/>
    <div id="logo"/>
</div>

Solution

  • First of all, you can't use the same id more than once per page - they must be unique. Change the ids to class names instead and fix your selectors accordingly.

    For your layout issue, adding clear:right; to the divs should do the trick.

    What is causing this?

    The divs are floating, so they'll try to fit in whatever space is available, and you apparently have enough space in the container to fit two side by side.