Automatically center HTML elements horizontally

Web programming topics
Post Reply
User avatar
Nipuna
Moderator
Moderator
Posts: 2729
Joined: Mon Jan 04, 2010 8:02 pm
Location: Deraniyagala,SRI LANKA

Automatically center HTML elements horizontally

Post by Nipuna » Fri Aug 10, 2018 4:29 pm

Today I am going to show you a simple code segment which will save you a lot of time.
Using this you can easily center any HTML element horizontally on all resolutions.

Here is the HTML part

Code: Select all

<div class="main-div">
    <div>Div 1</div>
    <div>Div 2</div>
    <div>Div 3</div>
</div>
This is where we do our magic. CSS

Code: Select all

.main-div{
 // This is what centers our elements
    text-align: center;
}
.main-div div{
 
// these all just to make the elements look good 
    width : 100px;
    background-color: red;
    margin: 10px 0;
    color: white;
    text-align: center;

// This is the important part
    display: inline-block;
}
Last edited by Nipuna on Sat Aug 11, 2018 9:13 pm, edited 1 time in total.
Reason: Corrected a syntax error
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

Re: Automatically center HTML elements horizontally

Post by Neo » Fri Aug 10, 2018 6:13 pm

I have no idea why I'm very bad at learning HTML and CSS correctly. You are an expert, so your quick tips will surely helpful. Keep up the good work.
User avatar
Nipuna
Moderator
Moderator
Posts: 2729
Joined: Mon Jan 04, 2010 8:02 pm
Location: Deraniyagala,SRI LANKA

Re: Automatically center HTML elements horizontally

Post by Nipuna » Fri Aug 10, 2018 7:33 pm

Neo wrote:
Fri Aug 10, 2018 6:13 pm
I have no idea why I'm very bad at learning HTML and CSS correctly. You are an expert, so your quick tips will surely helpful. Keep up the good work.
Thank you Neo, Yeah I have seen many expert programmers have problems learning and coding HTML and CSS but they are very good at other languages, I think these syntax maybe bothering them.

Anyway Thank you Neo, If I am at a place right now, you and Expertcore helped me a lot for that.. Looking at my early posts I always remember how much I've learned from here and you at my early stages :)
Post Reply

Return to “Web programming”