Div中的中心Div,宽度为自动

时间:2016-11-09 11:28:52

标签: html css

我在Div1里面有一个Div1和Div2 Div2中有图像和可变长度文本,我想将Div2的宽度保持为自动并将其居中在Div1中。

如下所述:

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

我正在尝试创建它但面临问题以覆盖背景Div到文本和图像,实际上我想将Div高度和宽度保持为自动但它没有按预期工作:

http://jsfiddle.net/2vhr4nLz/

3 个答案:

答案 0 :(得分:1)

如果我已正确理解您的问题,您应该使用css3 flexbox

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

在css上方将创建以下布局,您可以在工作片段中看到文本和图像将相对于彼此垂直中间对齐:

+---------------------------------------+
|            |  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       |
+---------------------------------------+

&#13;
&#13;
.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;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果我已理解,您可以将所有内容包装成a,然后将其添加到您的CSS

.wrapper {width:100%; text-align: center }

答案 2 :(得分:0)

For Auto width: You can use CSS3 Flexbox.

For fixed width:   

I modified your code and following are the changes;

    HTML:
    <div class="div1">
       <div class="div2">
          <img src="#">
          <span >Vertically Center Text Here</span>
       </div>
    </div>

    CSS:

    .div1 {
      background: red;
      padding: 20px;
      width: 100%;
    }

    .div2 {
      background: white;
      margin: auto;  
      width: 350px;
    }