Home > Blockchain >  Is it possible to force center a div in html no matter what is its class or its inner div classes?
Is it possible to force center a div in html no matter what is its class or its inner div classes?

Time:11-11

I am trying to center a div that has a few inner div with some classes. For example:

<div >
   <div >
      <article >
        ...
      </article>
   </div>
</div>

Assume we don't know what classes one, two, and three are. Is it possible to center horizontally <div > and everything inside?

I have tried for example text-align: center; as style but it didn't work.

UPDATE:

Actually, tacoshy's recommendation worked, but it is not exactly what I want. Please see these drawings:

This is before applying tacoshy's recommendation:

enter image description here

This is after applying his recommendation:

enter image description here

And this is what I want:

enter image description here

Is is possible to make the books closer together at the center?

CodePudding user response:

Why not using CSS Grid? (don't if you are using bootstrap with the css grid option)

.one {
            display: grid;
            background-color: white;
            width: 80vw;
            height: 80vh;
            margin: 10vh 10vw;
        }
        .two {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            grid-template-rows: 1fr;
            grid-column-gap: 10px;
            grid-row-gap: 0;
        }
        .three {
            background-color: yellow;
            border: 1px solid black;
            width: 20vw;
            height: 100%;
        }
        .three:first-child {
            justify-self: end;
        }
        .three:last-child {
            justify-self: start;
        }
<div >
    <div >
        <article >
            ...
        </article>
        <article >
            ...
        </article>
    </div>
</div>

CodePudding user response:

To center an element, the best way in my opinion is by using Flexbox. You just got to add those 3 properties to the parent :

  • display: flex
  • justify-content: center
  • align-items: center

So in your exemple, I believe it's the body if you want to center the only div on your page. Otherwise, you need a way, by aiming a div using an ID instead of class, or with :nth-child(n).

text-align: center works only for text or other elements with display: inline

  • Related