(编辑:jimmy 日期: 2024/10/30 浏览:2)
在写样式中,我们可以经常看到这样的情况
代码如下
<div style="width: 300px;border: 4px solid #000;margin: 20px;padding: 2px;"> 父元素 <div style="border: 1px solid blue;height: 100px;white-space: nowrap;"> <span>子元素子元素子元素子元素子元素子元素子元素子元素子元素子元素子元素子元素子元素子元素子元素子元素子元素子元素子元素子元素</span> </div> </div>
如果你仔细思考过这个现象的话,why? 可能会问子元素不应该撑开父元素的宽度吗?就想撑开父元素的高度一样。why? 那么如何让这个子元素的父元素撑开这个宽度呢?这里提供两种解决方案。
1. display: inline-block
布局样式如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <style> #box1 { width: 500px; height: 200px; border: 2px solid blue; padding: 10px; } #box2 { white-space: nowrap; display: inline-block; } #box3 { width: 300px; height: 200px; background-color: blueviolet; display: inline-block; vertical-align: middle; } #box4 { width: 400px; height: 200px; background-color: black; display: inline-block; vertical-align: middle; } </style> <body> <div id="box1"> <div id="box2"> <div id="box3"></div> <div id="box4"></div> </div> </div> </body> </html>
结果如图,box3和box4撑开了box2的宽度
2. display: inline-flex
布局样式如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <style> #box1 { width: 500px; height: 200px; border: 2px solid blue; padding: 10px; } #box2 { white-space: nowrap; display: inline-flex; } #box3 { width: 300px; height: 200px; background-color: blueviolet; vertical-align: middle; } #box4 { width: 400px; height: 200px; background-color: black; vertical-align: middle; } </style> <body> <div id="box1"> <div id="box2"> <div id="box3"></div> <div id="box4"></div> </div> </div> </body> </html>
效果如下图