0

I'm having trouble centering a section in CSS. If you need more information let me know.

I already tried text-align: center;

CSS code:

    #example{
        margin: auto;
        max-width: 1000px; 
}

HTML

<section id="example"> 
        <br>
        <hr>
        <div class="icon">
            <img src="Other/icon.png">
            New icon
        </div>

        <hr>
        <br>

        <a href="http://google.com" id="example">
                 <div class="box">
                        <div class="boximg" >
                                <img src="./alt/logo.png">
                        </div>  
                            <div class="text">
                        <p>Logo</p>
                        </div>  
                </div>
            </a>   
</section>

I hope someone can help.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
hypern00b
  • 53
  • 1
  • 7
  • Possible duplicate of [How to horizontally center a
    in another
    ?](https://stackoverflow.com/questions/114543/how-to-horizontally-center-a-div-in-another-div)
    – Heretic Monkey Feb 09 '18 at 22:32

2 Answers2

0

I would recommend wrapping the section inside a <main> tag and applying the following CSS:

main {
    display: flex;
    justify-content: center;
}

This will center the section however it is of course possible that you already have a <main> tag and dont want to turn the main portion of your page into a flexbox. In that case you can apply the flexbox CSS to your <section> and then wrap all of the section content in a div.

Here is an example of it with the main tag as a flexbox: https://jsfiddle.net/mywtec07/

Here is an example with the section as the flexbox and a div wrapping all the content: https://jsfiddle.net/6898txaL/1/


Alternatively you can center the section without adding any extra html. Simply apply the following CSS:

#example {
    display: block;
    margin: 0 auto;
    width: 300px;
    text-align: center;
}

You can see an example here: https://jsfiddle.net/qxeppj62/1/

Aonghas M
  • 1,863
  • 2
  • 10
  • 20
0

      #example{
        max-width: 1000px; 
      }

      .center {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%); 
        -ms-transform: translate(-50%, -50%); /* IE 9 */
        -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */       
      }
      
      .center-text {
        text-align: center;
      }
<section id="example" class="center">
  <hr>
  <div class="icon">
    <img src="Other/icon.png">New icon
  </div>
  <hr>
  <a href="http://google.com">
    <div class="center-text">
      <div class="boximg" >
        <img src="./alt/logo.png">
      </div>  
      <div class="text">
        <p>Logo</p>
      </div>  
    </div>
  </a>   
</section>
antelove
  • 3,216
  • 26
  • 20