【问题标题】:CSS problem with centering text when float:left is used使用 float:left 时文本居中的 CSS 问题
【发布时间】:2021-09-10 10:11:32
【问题描述】:

我想让我的文本居中,如下所示:

我尝试了几种方法,但没有任何效果。

Aligning a float:left div to center?

看起来需要float:left,当我们想要并排放置两个 div 时

Two divs side by side - Fluid display

这个东西可以用,但我需要左边的文本在盒子中间居中显示。

我的代码如下:

         <figure class="linkbox">
         <a class="linkurl" href="http://www.deckchair.com/" target="blank">
        <div class="links">Deckchair</div>
        <div class="desc">Text content
        </div>
        <div style="clear:both"></div>
        </a>
        </figure>

CSS

 .links {
 display:flex;
 flex-wrap:wrap;
 justify-content:center;
 align-items:center;
 float:left;
 font-weight:bold; 
font-size:large; 
 min-width:100px;
  }

   .desc {
  display:grid;
 text-align:justify;
 margin-right: 5px;
 margin-left: 20%;
  }

是否有任何选项可以使文本在左侧居中并保留页面的响应能力?

【问题讨论】:

  • 我建议你阅读更多关于 flexbox 的内容,有了这个 css 属性,你不需要向左浮动来并排对齐元素

标签: html css


【解决方案1】:

首先,我建议不要将多个 div 包装到一个锚标记中。 这是我的代码和小提琴: https://jsfiddle.net/nwxvzs1f/2/

<figure class="linkbox">
     <a class="linkurl" href="http://www.deckchair.com/" target="blank"></a>
    <div class="links">Deckchair</div>
    <div class="desc">Text content
    </div>
    <div style="clear:both"></div>
    </figure>

.links {


display:flex;
 flex-wrap:wrap;
 justify-content:center;
 align-items:center;
 float:left;
 font-weight:bold; 
font-size:large; 
 min-width:100px;
 width:50%;
 background-color: grey;
 height:100%;
  }

   .desc {
  display:grid;
 text-align:justify;
 margin-right: 5px;
 margin-left: 20%;
 width:50%;
  }
  .linkbox {
    height:300px;
    display:block;
    background-color: red;
    }

如果这不是您要搜索的内容,欢迎您完善您的问题。

【讨论】:

  • 基本上看起来我已经完全忘记了宽度和高度属性。由于宽度完美,我对高度有问题。在您的代码中,.linkbox 被严格定义为 300px。就我而言,它的高度是灵活的。可能这就是为什么 height 属性在我的情况下不起作用的原因。
  • @MKR 但“.linkbox”的高度也可以是“height:100vh;”或者至少将其设置为“100%”并且它是相对于父 div 的。
  • 我用了 height: auto;它与 100% 相同。但在链接中,高度 % 值根本不起作用。我需要像素或至少 vh 单位。然而,它们的位置并不相同,因为文本长度在盒子 (.desc) 中是不同的。
猜你喜欢
  • 2012-06-16
  • 2011-04-27
  • 2015-01-26
  • 1970-01-01
  • 1970-01-01
  • 2019-03-20
  • 1970-01-01
  • 2022-07-21
  • 1970-01-01
相关资源
最近更新 更多