Problem with matrix if statement for hero image other content ends up in my div
The problem is that the if statements are not nested properly. If your matrix does not contain the cta block for example then the 2 closing div tags will never be output, which obviously destroys the layout.

The bigger question for me is why you would want to separate the fields into different blockTypes at all. An easier approach would be to create one blockType (called 'imageHero' for example) with all 5 fields in it ('image', 'heading', 'subHeading', 'ctaEntry', 'ctaText'), which you could access directly. In this way, the blockTypes could be used for different 'types' of hero, rather than for separating out a single hero's fields.

{% for block in entry.hero %}

    {% if blocktype == 'imageHero'%}

        {% set image = block.heroimage.first() %}
        {% if image %}
            &lt;div class="hero" style="background: url('{{ image.url }}') no-repeat scroll 50% 50% / 100% auto rgba(0, 0, 0, 0);"&gt;
                &lt;div class="container" style="color:white;"&gt;
                    {% if block.heading %}
                        &lt;h1&gt;{{ block.heading }}&lt;/h1&gt;
                    {% endif %}
                    {% if block.subHeading %}
                        &lt;h2&gt;{{ block.heading }}&lt;/h2&gt;
                    {% endif %}
                    {% if block.ctaEntry and block.ctaText %}
                        &lt;a href="{{ block.ctaEntry.first.url }}" class="button"&gt;{{ block.ctaText }}&lt;/a&gt;
                    {% endif %}
                &lt;/div&gt;
            &lt;/div&gt;
        {% endif %}

    {% endif %}

{% endfor %}