Max Max - 3 months ago 7
CSS Question

css width inherited from inline-block element



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>





I want the
<div>
to be centered and to have the same width as the
<h1>
.
The same thing with the text, but how can I set the width of the
<p>
to be the same as the
<h1>
?

Answer

To do this you can use display: table on div and set its width to 1%. After that you just use white-space: nowrap on h1 so it will stay in one line and text of p element will adjust to that width.

div {
  border: 1px solid black;
  text-align: center;
  display: table;
  margin: 0 auto;
  width: 1%;
}
h1 {
  white-space: nowrap;
}
<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>

Comments