search

Home  >  Q&A  >  body text

When should I consider using position to position an element instead of flex box?

<p><br /></p> <pre class="brush:php;toolbar:false;"><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> #dn { width: 400px; height: 400px; padding: 20px; border: 2px solid #cd1313; } .box1 { width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; text-align: center; font-weight: bold; color: white; font-size: 24px; background-color: #000000; } </style> </head> <body> <div id="dn" class="boxn"> Lorem, ipsum dolor sit amet consectetur adipisicing elit. Architecto ducimus repudiandae inventore iste porro distinctio necessitatibus incidunt accusamus facilis obcaecati! hey namen <div id="d1" class="box1"> Child </div> Lorem ipsum dolor sit amet consectetur adipisicing elit. Eaque deleniti quibusdam quod praesentium, soluta harum alias aperiam hic voluptatum natus? </div> </body> </html></pre> <p>我已经将box1显示为伸缩框。它不仅允许我水平对齐里面的项目(子),还允许我沿着交叉轴垂直对齐项目。然后我问自己,为什么我没有使用位置来居中的文字?那么后果会是什么呢?是因为我们不能在文本上应用位置吗?,如果项目是一个跨度框,我可以在其中应用位置吗?如果是,那么它不会产生问题,因为我们必须使用绝对位置来使它响应boxn。这个问题又长又烦人,但对我来说很重要。</p>
P粉914731066P粉914731066493 days ago636

reply all(1)I'll reply

  • P粉311464935

    P粉3114649352023-07-24 11:11:40

    When using position, you must define how many pixels on each side of the object are needed to position it. This is not very flexible. Imagine you have to measure/calculate/try how many pixels each object needs for different screen sizes, it's possible but it takes a lot of time and effort. So flexbox is easier to implement.

    With flexbox, your content will be more consistent. I mean, it calculates for you how many pixels you need on each side of the object. This will reduce the chance of off-target calculations. Therefore, all elements will be positioned the same way.


    reply
    0
  • Cancelreply