Reputation: 1399
As the title says, I would like to center an img in a div with a span beside it. The HTML is as follows:
<div>
<img src="http://www.openwebanalytics.com/wp-content/plugins/owa/modules/base/i/browsers/128x128/ie4.png">
<span>Text</span>
</div>
This is as far as I've gotten: https://jsfiddle.net/qhpfoqng/2/. As you can see, it centers BOTH as if they were one element, when I really just want it to center the img only. The end product should have the img centered horizontally in the div with the span to the right of it.
Upvotes: 0
Views: 74
Reputation: 31
You can do this:
For this example, I used width: 40%, that means 100% - 40% / 2 = 30%; so margin-left: 30%, and that will center your image.
div {
width: 350px;
border: 1px black solid;
}
img {
width: 40%;
margin-left: 30%;
vertical-align: middle;
}
span {
font-size: 200%;
}
Upvotes: 0
Reputation: 131
Add the css as follows:
div {
margin:0 auto;
width: 350px;
text-align: center;
border: 1px black solid;
}
Upvotes: 1
Reputation: 56753
Just remove the span
from the document flow by setting position: absolute;
and then use some CSS magic to position it where you want it to be:
div {
width: 350px;
text-align: center;
position: relative;
border: 1px black solid;
}
img {
vertical-align: middle;
}
span {
font-size: 200%;
display: inline-block;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
<div>
<img src="http://www.openwebanalytics.com/wp-content/plugins/owa/modules/base/i/browsers/128x128/ie4.png">
<span>Text</span>
</div>
For that method to work, the surrounding div
needs to be positioned (any position value other than the default static
).
https://jsfiddle.net/qhpfoqng/4/
Upvotes: 1