您的位置:

CSS技巧:如何实现文本两端对齐排版

在网页设计中,排版是前端工程师不可避免的问题之一,如何让文本按照一定的规则排列是我们需要解决的问题。本文将介绍如何通过CSS实现文本两端对齐排版。

一、单行文本两端对齐排版

单行文本排版模式比较简单,可以通过text-align:justify属性实现两端对齐。下面是示例代码:

p{
  text-align:justify;
  text-justify:distribute-all-lines;
}

上面的代码中,text-align:justify属性用于水平对齐文本,text-justify:distribute-all-lines用于让文本两端对齐。

二、多行文本两端对齐排版

对于多行文本排版,采用text-justify属性依然可以做到两端对齐,但是有些浏览器并不支持这个属性。另外,使用text-justify实现的两端对齐不会考虑单词的意义,这也可能会带来排版上的问题。

此时,我们可以采用CSS3新增的hyphens属性,通过断词实现两端对齐。下面是示例代码:

p{
  text-align:justify;
  -moz-hyphens:auto;
  -webkit-hyphens:auto;
  hyphens:auto;
}

使用hyphens:auto属性后,浏览器会自动根据单词的意义将文本进行分行和断词,使得文本更加美观。

三、弹性盒子实现文本两端对齐排版

CSS3中的弹性盒子模型可以更加方便地实现文本两端对齐。在弹性盒子中,只要设置对齐方式为justify-content:center,就可以实现文本两端对齐。下面是示例代码:

.box{
  display:flex;
  justify-content:center;
  text-align:justify;
}

.box p{
  flex: 1;
  margin-right: 1rem;
}

上面示例中,设置了box的display属性为flex,justify-content属性为center,意味着box中的元素水平对齐方式是两端对齐。而内部的p元素是弹性盒子的一个子元素,flex属性为1表示按照弹性盒子模型进行布局,并将其右外边距设置为1rem,这样可以保证在文本中每个单词间距相等,看起来更加美观。

四、JavaScript实现文本两端对齐排版

如果以上方法都无法满足要求,那么我们可以用JavaScript实现文本两端对齐排版。实现方法是将一段文本分成多个词,然后通过JavaScript计算出将每一行的单词进行拉伸,使得每一行的单词间距相等,从而实现两端对齐。具体实现可以参考以下示例代码:

function justifyText(element, maxWidth) {
  var words = element.innerHTML.split(' ');
  //首先将文本拆分成多个单词

  var longString = '';
  for (var i = 0; i < words.length; i++) {
    var word = words[i];
    var clone = element.cloneNode(true);
    clone.innerHTML = word;
    document.body.appendChild(clone);
    var width = clone.offsetWidth;
    document.body.removeChild(clone);

    if (width > maxWidth) {
      longString += '
' + word; } else if (longString) { element.innerHTML = justifyLine(longString.trim(), maxWidth); longString = word; } else { longString = word; } } if (longString) { element.innerHTML = justifyLine(longString.trim(), maxWidth); } } function justifyLine(line, maxWidth) { var words = line.split(' '); var numSpaces = words.length - 1; var wordsWidth = 0; for (var i = 0; i < words.length; i++) { var clone = document.createElement('div'); clone.style.display = 'inline-block'; clone.style.visibility = 'hidden'; clone.innerHTML = words[i]; document.body.appendChild(clone); var width = clone.offsetWidth; document.body.removeChild(clone); wordsWidth += width; } var totalSpaceWidth = maxWidth - wordsWidth; var averageSpaceWidth = totalSpaceWidth / numSpaces; var leftSpaces = numSpaces / 2; var justifiedLine = ''; for (var i = 0; i < words.length; i++) { justifiedLine += words[i]; if (i < words.length - 1) { var numSpacesToInsert = i < leftSpaces ? Math.ceil(averageSpaceWidth) : Math.floor(averageSpaceWidth); for (var j = 0; j < numSpacesToInsert; j++) { justifiedLine += ' '; } } } return justifiedLine; } //使用 var element = document.getElementById('target'); var maxWidth = 200; justifyText(element, maxWidth);

以上代码实现了文本拆分成单词,通过计算每一个单词的宽度得出每一行需要填充的空格数量,从而实现文本两端对齐的效果。

CSS技巧:如何实现文本两端对齐排版

2023-05-16
CSS文本两端对齐的详细阐述

2023-05-20
如何在CSS中垂直对齐文本?

2023-05-12
CSS文字对齐方式的详细阐述

2023-05-21
when-present<#else>when-missing. (These only cover the last step of the expression; to cover the whole expression, use parenthesis: (myOptionalVar.foo)!myDefault, (myOptionalVar.foo)?? ---- ---- FTL stack trace ("~" means nesting-related): - Failed at: ${item.id} [in template "article/detail/index.ftl" at line 48, column 106] ---- Java stack trace (for programmers): ---- freemarker.core.InvalidReferenceException: [... Exception message was already printed; see it above ...] at freemarker.core.InvalidReferenceException.getInstance(InvalidReferenceException.java:134) at freemarker.core.EvalUtil.coerceModelToTextualCommon(EvalUtil.java:481) at freemarker.core.EvalUtil.coerceModelToStringOrMarkup(EvalUtil.java:401) at freemarker.core.EvalUtil.coerceModelToStringOrMarkup(EvalUtil.java:370) at freemarker.core.DollarVariable.calculateInterpolatedStringOrMarkup(DollarVariable.java:104) at freemarker.core.DollarVariable.accept(DollarVariable.java:63) at freemarker.core.Environment.visit(Environment.java:371) at freemarker.core.IteratorBlock$IterationContext.executedNestedContentForCollOrSeqListing(IteratorBlock.java:321) at freemarker.core.IteratorBlock$IterationContext.executeNestedContent(IteratorBlock.java:271) at freemarker.core.IteratorBlock$IterationContext.accept(IteratorBlock.java:244) at freemarker.core.Environment.visitIteratorBlock(Environment.java:645) at freemarker.core.IteratorBlock.acceptWithResult(IteratorBlock.java:108) at freemarker.core.IteratorBlock.accept(IteratorBlock.java:94) at freemarker.core.Environment.visit(Environment.java:335) at freemarker.core.Environment.visit(Environment.java:341) at freemarker.core.Environment.visit(Environment.java:341) at freemarker.core.Environment.process(Environment.java:314) at freemarker.template.Template.process(Template.java:383) at org.springframework.web.servlet.view.freemarker.FreeMarkerView.processTemplate(FreeMarkerView.java:332) at org.springframework.web.servlet.view.freemarker.FreeMarkerView.doRender(FreeMarkerView.java:266) at org.springframework.web.servlet.view.freemarker.FreeMarkerView.renderMergedTemplateModel(FreeMarkerView.java:220) at org.springframework.web.servlet.view.AbstractTemplateView.renderMergedOutputModel(AbstractTemplateView.java:181) at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:314) at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1431) at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1167) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1106) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:979) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:903) at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:564) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885) at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:205) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at com.software.filter.HttpSpiderIdentifyFilter.doFilter(HttpSpiderIdentifyFilter.java:51) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:340) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:896) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1744) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52) at java.base/java.lang.VirtualThread.run(VirtualThread.java:309)