从内联块元素

时间:2016-08-06 16:15:53

标签: html css html5 css3



body {
  text-align: center;
}
div {
  display: inline-block;
  background: #f3f3f3;
}

<body>
  <div>
    <h1>Lorem Ipsum</h1>
    <p>Sed salvia readymade, pour-over delectus art party raw denim consequat. Man bun pinterest nisi, incididunt flexitarian try-hard mollit fugiat asymmetrical bushwick waistcoat et synth organic brooklyn.</p>
  </div>
</body>
&#13;
&#13;
&#13;

我希望<div>居中并与<h1>具有相同的宽度。 与文字相同,但如何将<p>的宽度设置为与<h1>相同?

3 个答案:

答案 0 :(得分:3)

要执行此操作,您可以display: table使用div并将其width设置为1%。之后,您只需在white-space: nowrap上使用h1,这样它就会停留在一行中,p元素的文字将调整到该宽度。

&#13;
&#13;
div {
  border: 1px solid black;
  text-align: center;
  display: table;
  margin: 0 auto;
  width: 1%;
}
h1 {
  white-space: nowrap;
}
&#13;
<div>
  <h1>Lorem Ipsum</h1>
  <p>Sed salvia readymade, pour-over delectus art party raw denim consequat. Man bun pinterest nisi, incididunt flexitarian try-hard mollit fugiat asymmetrical bushwick waistcoat et synth organic brooklyn.</p>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

使用width: 0,您可以使父div缩小而忽略段落,只考虑标题。然后使用min-width: 100%,您可以强制它与div一样宽。

body {
  text-align: center;
}
div {
  display: inline-block;
  background: #f3f3f3;
}
p {
  width: 0;
  min-width: 100%;
}
<div>
  <h1>Lorem Ipsum</h1>
  <p>Sed salvia readymade, pour-over delectus art party raw denim consequat. Man bun pinterest nisi, incididunt flexitarian try-hard mollit fugiat asymmetrical bushwick waistcoat et synth organic brooklyn.</p>
</div>

答案 2 :(得分:-1)

{
text-align:center;
}

div

{
width:200px;
  display: inline-block;
  background: #f3f3f3;
}

div p

{
text-align:justify;
}