A_user A_user - 25 days ago 10
HTML Question

Center Div inside Div with width as auto

I have a Div1, and Div2 inside Div1.

Div2 has image and variable length text in it, I want to keep the width of Div2 as auto and center it in the Div1.

As described below:

+-------------------------------------------------------------------+
| Div1 |
| +-------+--------------------+ |
| | Image | Some Test Text | <- Div2: Width:auto; |
| +-------+--------------------+ |
| |
+-------------------------------------------------------------------+


I am trying to create it but facing issue to cover the background Div to text and image, actually I want to keep Div height and width as Auto but it is not working as expected:

http://jsfiddle.net/2vhr4nLz/

Answer

If I've understood your question correctly, you should use css3 flexbox for this.

.text-and-image-holder {
  justify-content: center;
  align-items: center;
  display: flex;
}

Above css will create the following layout as you can see in working snippet that text and image will be vertically middle aligned with respect to each other:

+---------------------------------------+
|            |  Lorem ipsum dolor sit   |
|            |  amet, lorem ipsum dolor |
|            |  sit amet, lorem ipsum   |
|   <img>    |  dolor sit amet, lorem   |
|            |  ipsum dolor sit amet,   |
|            |  lorem ipsum dolor sit   |
|            |  amet, lorem ipsum       |
+---------------------------------------+

.image-style {
  margin-right: 20px;
} 

.text-style {
  font-size: 15px;
}

.text-and-image-holder {
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
  background: red;
  padding: 20px;
  display: flex;
}
<div class="text-and-image-holder">
  <img src="http://placehold.it/30x30" class="image-style">
  <div class="text-style">Vertically Center Text Here</div>
</div>
<div class="text-and-image-holder">
  <img src="http://placehold.it/30x30" class="image-style">
  <div class="text-style">Very long text Vertically Center Here and lorem ipsum dolor sit amet.</div>
</div>

Comments