Center elemement without centering all chidren recursively?

I wish to center all children within an element without centering all of their chilren.

<Col style={{ textAlign: "center" }}>
  <Space>...</Space>
  <div>...</div>
</Col>

In this example, I am using antd. The library should not matter though. I wish to add center the Space and div element but not any of Space’s or div’s elements. Using textAlign will center every element contained within its scope, which is not what I want.

14 thoughts on “Center elemement without centering all chidren recursively?”

  1. Flexbox is the solution. For horizontal centering, use justify-content:

    Colu { 
        display: flex; 
        justify-content: center;
        /*           or: space-evenly */
    }
    
    Colu, Space, div { 
        border: 1px solid;
        padding: 5px;
    }
    
    Space, div { 
        display: inline-block;
        width: 100px; 
    }
    <Colu>
      <Space>abc</Space>
      <div>def</div>
    </Colu>

    Note I had to change Col in this demo, as Col is an existing HTML element that may only occur in a colgroup within a table element, and cannot have content.

    Reply
  2. You could achieve via flex

    {display: 'flex',alignItems: 'center',flexDirection: 'column'}
    

    Example in HTML+CSS

    #demo{
      display:flex;
      align-items:center;
      flex-direction:column;
    }
    <div id="demo">
      <span style="width:100px;background:green;">
       <p>2nd child</p>
      </span>
      <button>first<button>
    <div>
    Reply

Leave a Comment