按钮通常是在 HTML <button>、<input> 或者 <a> 标签的帮助下创建的。
创建按钮时,当按钮包含长文本时,我们可能需要添加换行符。
添加换行符的方法
换行的最简单方法是在文本上使用 <br> 标签。
它用于插入单个换行符。
使用 <br> 标记创建带有换行符的按钮的示例:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> </head> <body> <h1>Button with line break</h1> <button type="submit">My<br />Button</button> </body> </html>
添加换行符的另一种方法是使用 CSS word-break 属性,该属性指定单词到达行尾时应如何换行。
将按钮文本放在 <span> 元素中并为其设置样式。
使用 word-break 属性的“保留所有”值并设置宽度。
使用 word-break 属性创建带有换行符的按钮的示例:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <style> span { display: block; width: 50px; padding: 0 20px; margin: 0; word-break: keep-all; text-align: center; } </style> </head> <body> <h1>Button with word-break</h1> <button type="submit"> <span>My Button Example</span> </button> </body> </html>
添加换行符的另一种方法是使用 flex-wrap 属性及其“wrap”值,它定义了灵活项目将在需要的地方换行。
其中我们还需要为按钮设置宽度属性。
使用 flex-wrap 属性创建带有换行符的按钮的示例:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <style> .btn { display: flex; flex-wrap: wrap; width: 80px; padding: 10px; } </style> </head> <body> <h1>Button with flex-wrap</h1> <button class="btn" type="submit">My Button Example</button> </body> </html>
让我们看另一个例子,我们为按钮使用另外的样式和 onclick 属性。
创建带换行符的样式按钮的示例:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <style> .btn { display: inline-block; padding: 10px 25px; margin: 4px 2px; background-color: #1c87c9; border: 3px solid #095484; border-radius: 5px; text-align: center; text-decoration: none; font-size: 20px; color: #fff; cursor: pointer; } </style> </head> <body> <button class="btn" onclick="window.location.href='https://www.onitroad.com';" type="submit"> Click <br />Me! </button> </body> </html>
正如我们所提到的,也可以使用 <a> 和 <input> 元素创建按钮。
让我们看看如何在使用这些元素创建的按钮中添加换行符。
在使用 HTM <a> 标签创建的按钮中添加换行符的示例:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <style> .btn { display: flex; flex-wrap: wrap; cursor: pointer; width: 50px; padding: 10px; text-decoration: none; background-color: lightblue; text-align: center; border-radius: 10px; } </style> </head> <body> <h1>Button with the <a> tag </h1> <a class="btn" href="https://www.onitroad.com/learn-git.html">Learn Git</a> </body> </html>
在下面的示例中,我们使用带有“normal”值的 white-space 属性并将自动换行属性设置为“break-word”。
在使用 HTM <input> 标签创建的按钮内添加换行符的示例:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <style> .btn { display: inline-block; width: 110px; white-space: normal; word-wrap: break-word; padding: 15px 25px; margin: 10px; background-color: lightblue; border: 2px solid #56a9de; border-radius: 5px; text-align: center; outline: none; font-size: 18px; color: #ffffff; cursor: pointer; } </style> </head> <body> <input type="button" class="btn" value="Some text" /> </body> </html>
日期:2020-06-02 22:15:04 来源:oir作者:oir