How to float an img left of text when the text is before it in the markup?

时间:2015-06-30 13:26:40

标签: css image css-float

I don't even know if this is possible. I'm trying to make image float left to the text (or text right to the image). I need content to be above image, as with a CSS query, for mobile devices, I'd like to remove formatting and have text remain above image.

https://jsfiddle.net/as1wj9sp/

I tried fixed positioning, but then the image doesn't comply to the rest of the layout.

* {
	padding: 0px;
	margin: 0px;
	list-style-type: none;
	font: 1em/1em Arial, Tahoma, Helvetica, sans-serif;
}
#content {
	margin: auto;
	background: #FCC;
	padding: 10px;
}
#index {
	background: #063;
	padding: 2px;
	overflow: hidden;
}
#index h1 {
	float: right;
}
#index img {
	display: block;
	float: left;
	max-width: 90%;
}
<div id="content">
    <div id="index"><h1>The Right Ingredients At The Real Dose asdadasda ad ad as dasdas as das das das dasdas dd asd asdsadasdasd asdasdasd asdasdasd asdasdas dad asd as</h1>
    <img src="img/image.jpg" alt="test" width="200" height="200" /></div>
</div>

2 个答案:

答案 0 :(得分:2)

I'd change both elements to be display: block and then you'll probably need a width of the elements, say 50% each for simplicity.

Finalize this concept using a @media-query for mobile devices.

Something like this:

    #index h1 {
        float: right;
        display: block;
        width: 60%;
    }
    #index img {
        display: block;
        float: left;
        width: 40%;
    }

/* Or whatever max-width you want */
    @media (max-width: 768px) {
        #index h1,
        #index img {
            float: left;
            width: auto;
        }
    }

答案 1 :(得分:1)

This answer doesn't use floats, but it does achieve what you are trying to do. If you don't need to support old browsers with this, you can use display: flex; and order. It works in all modern browsers.

JSFiddle Example

* {
    padding: 0px;
    margin: 0px;
    list-style-type: none;
    font: 1em/1em Arial, Tahoma, Helvetica, sans-serif;
}
#content {
    margin: auto;
    background: #FCC;
    padding: 10px;
}
#index {
    background: #063;
    padding: 2px;
    overflow: hidden;
    display: flex;
    display: -webkit-flex;
}
#index h1 {
    order: 2;
    -webkit-order: 2;
}
#index img {
    display: block;
    max-width: 90%;
    order: 1;
    -webkit-order: 1;
}
<div id="content">
    <div id="index">
        <h1>The Right Ingredients At The Real Dose asdadasda ad ad as dasdas as das das das dasdas dd asd asdsadasdasd asdasdasd asdasdasd asdasdas dad asd as</h1>
        <img src="img/image.jpg" alt="test" width="200" height="200" />
    </div>
</div>

The -webkit- prefixes are for Safari.