我需要显示从居中文本的左右边缘填充10px的左右边框.当所有文本都适合一行时没有问题,但是当文本占用多行时,包装内联块元素会延伸到其容器宽度的100%.
我需要一个纯CSS解决方案.
这是JSFiddle与问题的工作演示:https://jsfiddle.net/k8wrbctr/
这是HTML:
<div class="container"> <div class="borders-wrapper"><span>The title</span></div> <div class="borders-wrapper"><span>The title that takes up multiple lines</span></div> </div>
这是CSS:
.container { width: 200px; text-align: center; background-color: #ddd; } .borders-wrapper { display: inline-block; border-left: 2px solid black; border-right: 2px solid black; padding-left: 10px; padding-right: 10px; margin-bottom: 20px; }
这是结果:
| The title | | The title that takes up | | multiple lines |
这就是我想要实现的目标:
| The title | | The title that takes up | | multiple lines |
解决方法
I need to display left and right borders padded 10px away from left
and right edges
你需要给边距不填充.
when text takes up multiple lines the wrapping inline-block element
stretches to 100% of it’s container width
这是因为内容很长并且div将尽可能地延伸(达到父宽度)以在内容包装到下一行之前容纳内容.
你的div是内联块还有另外一个问题 – 如果内容少了,那么下一个div将在第一个div之后开始,而不是在它自己的行上.
解决方案(将div保持为内联块):
使用伪元素来破坏该行.
* { Box-sizing: border-Box; } .container { width: 200px; text-align: center; background-color: #ddd; } .borders-wrapper { display: inline-block; border-left: 2px solid black; border-right: 2px solid black; padding: 0px 10px; margin: 10px; } .borders-wrapper::after { content:"\A"; white-space:pre; }
<div class="container"> <div class="borders-wrapper"><span>The title</span></div> <div class="borders-wrapper"><span>The title that</span></div> <div class="borders-wrapper"><span>The title that takes up multiple lines</span></div> </div>
注意:
谢谢@Kaiido指出来.伪元素技巧不适用于其元素为内联块.为了使它工作,你在跨度上做填充/边距,并浮动div.然后使用变换技巧使其居中.有点复杂.
例:
* { Box-sizing: border-Box; } .container { width: 200px; text-align: center; background-color: #ddd; } .borders-wrapper { float: left; clear: left; position: relative; left: 50%; transform: translateX(-50%); margin: 0px auto; } .borders-wrapper > span { display: inline-block; padding: 0px 10px; margin: 10px; border-left: 2px solid black; border-right: 2px solid black; } .container:after { content:''; display:block; clear: both; } .div2 { width: 400px; }
<div class="container"> <div class="borders-wrapper"><span>The title</span></div> <div class="borders-wrapper"><span>The title that</span></div> <div class="borders-wrapper"><span>The title that takes up multiple lines</span></div> </div> <br /> <div class="container div2"> <div class="borders-wrapper"><span>The title</span></div> <div class="borders-wrapper"><span>The title that</span></div> <div class="borders-wrapper"><span>The really long title that takes up multiple lines in a large width</span></div> </div>