set div width to content without inline-block and

2020-07-14 09:14发布

I want some divs to get their width from their content. Display:inline-block does this, but I also want the divs to be under each other, not next to each other as floated.

Using float:left instead of inline-block does this, but I want the divs to be center aligned, not left aligned. How can I do this?

标签: css
4条回答
迷人小祖宗
2楼-- · 2020-07-14 09:49

on the parent div put white-space: pre-line; on the child divs add clear : both

#wrapper{ text-align: center; white-space: pre-line; }
#div1, #div2{

    display: inline-block;    
    clear: both;
    border: 1px solid grey;
    margin: 3px auto 3px auto;
    width: auto;

}

<div id="wrapper">
     <div id="div1" class="clearfix">some content here that is bigger</div>
     <div id="div2" class="clearfix">some content here</div>
</div>

http://jsfiddle.net/judsonmusic/8HCWp/

查看更多
女痞
3楼-- · 2020-07-14 09:49

Working jsFiddle Demo

Consider the following markup:

<div class="container">
    <div class="text">apple</div>
    <div class="text">banana</div>
    <div class="text">kiwi</div>
    <div class="text">orange</div>
</div>

Because you want to align your elements, you must use inline, then we will break them with :after:

.container {
    text-align: center;
}

.text {
    background: yellow;
    display: inline;
}

.text:after {
    content: '';
    display: block;
}
查看更多
淡お忘
4楼-- · 2020-07-14 09:58

html is

<div>
   abc <div style="margin:4px auto;width:100px;">div1</div><br/>
   abc <div style="margin:4px auto;width:100px;">div1</div><br/>
   abc <div style="margin:4px auto;width:100px;">div1</div><br/>
   abc <div style="margin:4px auto;width:100px;">div1</div><br/>
</div>

and style sheet is

div{
    border:1px solid;
    padding:10px;
    display:inline-block;
   }

check demo at http://jsfiddle.net/xupHN/

查看更多
男人必须洒脱
5楼-- · 2020-07-14 10:02

As mentioned in this thread, there's also a flex solution to this problem:

#container > p {
  border-bottom: 2px solid black;
}
    
#container {
  display: flex;
  flex-flow: column;
  align-items: flex-start;
}
<div id="container">
  <p>A text</p>
  <p>A text</p>
  <p>A longer text</p>
</div>


    

查看更多
登录 后发表回答