简体   繁体   中英

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

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> 

With width: 0 you can make the parent div shrink ignoring the paragraph, only taking the header into consideration. And then with min-width: 100% you can force it to be as wide as the 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> 

body

{
text-align:center;
}

div

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

div p

{
text-align:justify;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM