Web Analytics Made Easy -
StatCounter Trouble centering DIV - CodingForum

Announcement

Collapse
No announcement yet.

Trouble centering DIV

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Trouble centering DIV

    I've made a DIV that contains 3 divs: one div for an image, and two divs for text. Im trying to horizontally align that div on the middle for every resolution.

    Link to see DIV not centered
    Non-mobile link

    I have tried different solutions but none of them worked.

    HTML PAGE CODE
    Code:
    <div class="contenedorimagenindice">
    <div class="imagenindice"><img src="http://elamigoinformatico.es/wp-content/uploads/2016/08/leagueoflegendsindiceimg.jpg" /></div>
    <div class="imagenindicemovil"><img src="http://elamigoinformatico.es/wp-content/uploads/2016/08/LOLMovil.jpg" /></div>
    <div class="contenedortutoriales">Acceder a los tutoriales</div>
    <div class="contenedorerrores">Acceder a las soluciones</div>
    </div>
    CSS CODE
    Code:
    .contenedorimagenindice {
    	max-height: 266px;   
    	width: 100%;
    	max-width: 750px;
    	background-color: white;
    	float: left;
    	display:block;
    }
    
    .imagenindice {
    	max-height: 226px;
    	width: 100%;
    	max-width: 750px;
    	background-color: white;
    	float: left;
    	display:block;
    }
    
    .imagenindice img {
    	width: 100%;
    	height: 100%;
    }
    
    
    .imagenindicemovil {
    	max-height: 226px;
    	width: 100%;
    	max-width: 750px;
    	background-color: white;
    	float: left;
    	display: none;
    }
    
    
    .contenedortutoriales {
    	height:40px;
    	width: 50%;
    	background-color: #9DD009;
    	color: white;
            float: left;
            line-height: 40px;
            text-align: center;
    }
    
    .contenedorerrores {
    	height:40px;
    	width: 50%;
    	background-color: #9DD009;
    	color: white;
    	float: left;
    	line-height: 40px;
    	text-align: center;
    }
    
    .contenedortutoriales p:hover {
    	background-color: #8ab708;
        color: white;
    }
    
    .contenedorerrores p:hover {
    	background-color: #8ab708;
        color: white;
    }
    
    @media (max-width: 600px) { 
    
        .contenedorimagenindice {
        	margin-bottom: 50px;
        }
    
    	.contenedortutoriales {
    		width: 270px;
    		clear: both;
    	}
    
        .contenedorerrores {
        	width: 270px;
    		clear: both;
        }
    
        .contenedortutoriales a:hover {
    	background-color: #8ab708;
        color: white;
        }
    
        .contenedorerrores a:hover {
    	background-color: #8ab708;
        color: white;
        }
    
        .imagenindice {
        display: none;
        }
    
        .imagenindicemovil {
     display: block;
        }
    }
    Last edited by WishICouldCode; Sep 7, 2016, 02:39 PM.

  • #2
    Try this CSS:
    Code:
    .contenedorimagenindice {
    	max-height: 266px;   
    	width: 100%;
    	max-width: 750px;
    	background-color: white;
    [COLOR="#FF0000"]	//float: left;
    	margin: 0 auto;[/COLOR]
    	display:block;
    }
    Remove the float then add the margin-auto
    Evolution - The non-random survival of random variants.
    Physics is actually atoms trying to understand themselves.

    Comment


    • #3
      If all that's in it is an IMG, why have the DIV? What are you doing you couldn't just do to the IMG... if it's 100% width, why are you floating it? You can't center floats, though I'm assuming the thing you want centered is the one with the max-width... and why have hover states on paragraphs on elements that clearly are not grammatical paragraphs... are those going to be ANCHORS?

      Of course, endless pointless DIV for nothing mated to endless pointless classes for nothing are a bootcrap hallmark -- client came to me with that I'd tell them to put it down like Old Yeller and start over. Laundry list of how NOT to build a website -- hence the 36.7k of markup to deliver 1.89k of plaintext and two content images -- easily four to five times the code that should have been used for such a simple layout.

      In that same way, loading two images in the markup when only one is for mobile is ignoring something called "content orientation" -- you want it cropped just crop it rather than having both desktop and mobile blindly load it both ways. To that end, I see NO legitimate reason for said code to be significantly more than:

      Code:
      <div class="contenedorimagenindice">
      	<img
      		src="http://elamigoinformatico.es/wp-content/uploads/2016/08/leagueoflegendsindiceimg.jpg"
      		alt="DESCRIBE THIS IMAGE!!!"
      	>
      	<a href="#wherever">Acceder a los tutoriales</a>
      	<a href="#wherever">Acceder a las soluciones</a>
      <!-- .contenedorimagenindice --></div>
      with CSS being something like this:

      Code:
      .contenedorimagenindice {
      	overflow:hidden; /* wrap floats */
      	zoom:1; /* trip haslayout, wrap floats legacy IE if you care */
      	display:block;
      	max-width:750px;
      	margin:0 auto 1em;
      	padding-bottom:0.5em;
      }
      
      .contenedorimagenindice img {
      	display:block; /* prevent height and alignment oddities */
      }
      
      .contenedorimagenindice a {
      	float:left;
      	width:50%;
      	padding:0.5em 0;
      	text-align:center;
      	background:#9DD009;
      	color:#FFF;
      }
      
      .contenedorimagenindice a:active,
      .contenedorimagenindice a:focus,
      .contenedorimagenindice a:hover {
      	background:#8AB708;
      }
      
      @media (max-width:600px) {
      	.contenedorimagenindice {
      		width:270px;
      	}
      	.contenedorimagenindice a {
      		display:block;
      		float:none;
      		width:auto;
      	}
      }
      Removing a lot of the endless pointless redundant declarations from both the HTML and CSS. When you have things that share the same behaviors, declare them together! Also operating on the assumption those were hover states for a REASON like making them links to actually go somewhere. Semantics and proper markup FIRST before you just start throwing classes and DIV in there willy-nilly!

      ... and just as Carlin joked "not every ejaculation deserves a name" not every HTML element needs a bloody class on it!

      Hence why if you don't know what's wrong with idiocy like this:

      Code:
      <div class="collapse navbar-collapse navbar-collapse-1 navbar-hover">
      
      				<ul id="menu-menu-top" class="navbar-nav nav"><li id="menu-item-7" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-7">
      You might want to back away from the keyboard for a while... bootcrap, only thing you can learn from it is how NOT to build a website.

      I would also suggest you study up on LEGIBLE colour contrasts, because you don't have them. See "web content accessibility guidelines" for more.
      Walk the dark path, sleep with angels, call the past for help.
      https://cutcodedown.com
      https://medium.com/@deathshadow

      Comment


      • #4
        Thank you so much for posting. As you well said, Im not a coder and my code might be a bit silly, I will start studying coding at school in a few months and I just wanted to start learning it myself so I know something before getting in there.
        I'm gonna reply you and i'm not gonna try to say that you are wrong on anything you said, im just going to explain why i've done it.

        If all that's in it is an IMG, why have the DIV?
        I thought it had to be in a DIV because I wanted both text boxes "Acceder a los tutoriales" / "Acceder a las soluciones" to stay under the image and have the same width than the image, and the only way to do it is to put the image in a div. Obviously I was wrong.

        why are you floating it?
        This is one of my misstakes, as you said since its 100% width it doesnt need to float and thats one of the reasons to block the centering.

        why have hover states on paragraphs on elements that clearly are not grammatical paragraphs
        You are right. Hover should be applied to links instead of paragraphs.

        loading two images in the markup when only one is for mobile
        This is one of my misstakes. Can this really affect the navigation speed even if its only a small image?

        not every HTML element needs a bloody class on it!
        As far as I learnt, it doesnt really matter if its a class or an ID, thats why I decided to use classes rather than IDs.


        I have tested your code, and I thank you so much the time you invested on it, but im facing a problem. I think it has relation with the .contenedorimagenindice a { padding but i didnt manage to fix it.

        Click image for larger version

Name:	Css.jpg
Views:	1
Size:	37.0 KB
ID:	2270476

        I know i "coded" that thing very bad... But at least is probably the only thing I have to code, everything else is coded since its a wordpress theme.

        Why do you think colors are not legible? In the current div they are not properly set, but they will look green and white, it should be legible. If you are not only talking about the thread div colours i'd appreciate to know your opinion about the site colors.

        Again, thank you so much.
        Last edited by WishICouldCode; Sep 8, 2016, 10:21 AM.

        Comment


        • #5
          Originally posted by sunfighter View Post
          Try this CSS:
          Code:
          .contenedorimagenindice {
          	max-height: 266px;   
          	width: 100%;
          	max-width: 750px;
          	background-color: white;
          [COLOR="#FF0000"]	//float: left;
          	margin: 0 auto;[/COLOR]
          	display:block;
          }
          Remove the float then add the margin-auto
          Thank you so much, it works, but as I can see being non aligned was the smaller of my problems.

          Comment


          • #6
            I could not fix the problem that was showing with your code, but I managed to modify a bit my old code with your tips and sunfighter's message.
            I know its not the best, most likely because your code is extremely shorter than mine and is currently doing the same, but I had to try something myself.
            I modified it to make it crop rather than loading two different images as you said, and now its currently centered. Also setting paragraphs with clear: both styles, prevents text going into the div sides at every resoution, so its working now everywhere except on very small android screen. ( can check here )

            I want to thanks you both for your help, and if you can help me to fix your code I will gladly change it for mine since your looks way more optimal.
            Thanks you again.

            HTML
            Code:
            <div class="contenedorimagenindice">
            <div class="imagenindice"><img src="http://elamigoinformatico.es/wp-content/uploads/2016/08/leagueoflegendsindiceimg.jpg" /></div>
            <div class="contenedortutoriales"><a href="http://x">Acceder a los tutoriales</a></div>
            <div class="contenedorerrores"><a href="http://x">Acceder a las soluciones</a></div>
            </div>
            CSS
            Code:
            .contenedorimagenindice {
            	width: 60%;
            	background-color: white;
                    margin: 0 auto;
            }
            
            .imagenindice {
            	width: 100%;
            	background-color: white;
            	float: left;
            }
            
            .contenedortutoriales {
            	height:40px;
            	width: 50%;
            	background-color: #9DD009;
            	color: white;
                    float: left;
                    line-height: 40px;
                    text-align: center;
            }  
            
            .contenedorerrores {
            	height:40px;
            	width: 50%;
            	background-color: #9DD009;
            	color: white;
            	float: left;
            	line-height: 40px;
            	text-align: center;
            }
            
            .contenedortutoriales a:hover,
            .contenedorerrores a:hover {
            	background-color: #8ab708;
                color: white;
            }
            
            
            @media (max-width:600px) {
            	.contenedorimagenindice {
            		width:270px;
            	}
            	.contenedortutoriales {
            		display:block;
            		clear:both;
                            width: 100%;
            	}
            
            .contenedorerrores {
            		display:block;
            		clear:both;
                            width: 100%;
            	}
            }
            Last edited by WishICouldCode; Sep 8, 2016, 07:57 PM.

            Comment


            • #7
              Actually, the reason it's showing up wider than the image is your image is only 660px wide, not 750px... so change the max-width.

              Code:
              .contenedorimagenindice {
              	overflow:hidden; /* wrap floats */
              	zoom:1; /* trip haslayout, wrap floats legacy IE if you care */
              	display:block;
              	max-width:660px;
              	margin:0 auto 1em;
              	padding-bottom:0.5em;
              }
              
              .contenedorimagenindice img {
              	display:block; /* prevent height and alignment oddities */
              }
              
              .contenedorimagenindice a {
              	float:left;
              	width:50%;
              	padding:0.5em 0;
              	text-align:center;
              	text-decoration:none;
              	background:#9DD009;
              	color:#080;
              }
              
              .contenedorimagenindice a:active,
              .contenedorimagenindice a:focus,
              .contenedorimagenindice a:hover {
              	background:#8AB708;
              }
              
              @media (max-width:660px) {
              	.contenedorimagenindice img {
              			margin-left:-30px;
              	}
              }
              
              @media (max-width:570px) {
              	.contenedorimagenindice {
              		width:270px;
              	}
              }
              
              @media (max-width:570px),
              @media (max-width:30em) {
              	.contenedorimagenindice a {
              		display:block;
              		float:none;
              		width:auto;
              	}
              }
              Should do the trick - I target the media queries both by pixels and by em's since you should have dynamic fonts on the page -- aka measured in EM. The negative margin-left trick slides that image over to reveal the logo part properly, and the 660px makes it the ACTUAL size of the image.

              As to your questions:

              Originally posted by WishICouldCode View Post
              I thought it had to be in a DIV because I wanted both text boxes "Acceder a los tutoriales" / "Acceder a las soluciones" to stay under the image and have the same width than the image, and the only way to do it is to put the image in a div. Obviously I was wrong.
              HTML is for saying what things ARE, NOT what you want them to look like. Using a DIV just because you want a block style behavior is missing the point of HTML. DIV are semantically neutral, they apply no meaning and as such should be used when you've expended the style you can apply to the existing tags or to group sections of tags so you only need one class or ID, not many. The single DIV wrapping the image and two anchors is fine, it's grouping a section for style without saying what that style is... slapping extra block-level tags inside said div is just "div for nothing" as they aren't being used to do anything you couldn't directly apply to the elements inside them with CSS.

              If you are choosing your HTML based just on the default appearance and behavior, you're choosing all the wrong tags for all the wrong reasons.

              Originally posted by WishICouldCode View Post
              This is one of my misstakes. Can this really affect the navigation speed even if its only a small image?
              the impact is twofold. The first is a combination of memory and bandwidth. It's just more data. Even if the image is "small" you have to remember that the UA has to unpack it to raw data before displaying it... meaning mobile devices with their lesser free memory amounts will often drag if you have too many large images.

              The second problem is significantly more important -- handshaking. "first-load", aka cache empty first time someone visits the page, or should elements in the cache have been flushed to make room for new stuff (regardless of dicking with cache-control headers like Google claims) or just lacking significant free space to cache things (again, mobile) the browser has to ask for each file. These file requests involve four back-and-forth between the browser; Browser asks "do you have the file", the server says "yes, I have the file", the browser asks "may I have the file", the browser then says "sure, here it comes". Each direction these conversations take the same or more time than a "ping" to the server would... so if your ping time is 150ms, the total handshaking time is 600ms or more.

              Now, browsers can request multiple files at the same time (typically to a limit of 8) though overtaxed servers or busy shared connections can quickly decrease that number -- but between the first eight being considered "free" thanks to the overlap and the overall overlap the "rule of thumb" is that every file past the first eight adds 200ms to your page load average, a full second OR MORE worst-case scenario... So if you have a page built from 48 separate files, that's anywhere from 8 to 40 seconds of overhead the first time someone visits your site... and really anything over 20 seconds greatly increases the likelihood of users telling you to flush off, and going to some other site that doesn't take forever to load.

              ... which is where sites made from hundreds of separate files are so pathetic -- it's like "you have users? REALLY?"

              Your page is a ridiculous 1.7 megabytes spanning 52 files -- all to deliver 681 bytes of plaintext and two content images -- that's epic fail at web development particularly when one considers the ape-**** nutters 550k of CSS spanning 24 files on a site that to be frank likely doesn't need more than 32k of CSS in ONE file, the 522k of scripttardery on a page I see no legitimate reason to even have JavaScript... but it's built with bootcrap and turdpress; that's just par for the course with those crappy off the shelf solutions that were created by people who have ZERO business telling others how to build a website.

              The page in question? I see ZERO legitimate reason for it to be taking more than 96k in about a dozen files not counting the two content images. Particularly if you axe that goofy "loader" rubbish that you wouldn't need if the page wasn't such a bloated pig in the first place. Someone brought that to me as a client, I'd tell them to pitch it in the bin and start over.

              Originally posted by WishICouldCode View Post
              As far as I learnt, it doesnt really matter if its a class or an ID, thats why I decided to use classes rather than IDs.
              You missed my meaning, it's not the use of a class or ID that's the problem, it's that you threw them at EVERYTHING for no legitimate reason. If you have a wrapping element (like DIV) with a class or ID on it, and semantic tags inside said wrapper that are all recieving the same style, NONE of those child tags inside the wrapper should need classes! There is this sick trend right now of certain groups of ignorant fools saying "keep your selectors flat", "don't use ID's as selectors", and "don't use tags as child selectors" -- and they're full of manure. It's like they want people to write two to ten times the HTML and CSS making pages slower, then make these noodle-doodle claims that the result somehow "renders faster". Maybe if they didn't use two to ten times the HTML needed they wouldn't have render speed issues.

              You don't NEED to put a class or ID on everything... see how in my rewrite it doesn't need classes on the anchors or the images? JUST the DIV wrapping them? Yeah, that!

              Which is why garbage like bootcrap just pisses on every website it's used on, as it's based on slapping endless pointless presentational classes on everything, resulting in people slapping even MORE endless pointless classes to customize it, resulting in fat bloated slow websites where the developer ended up working harder, not smarter. I'll never understand how people can claim writing more code is "easier"... and that's exactly what bootcrap does to you; there's a reason I usually tell people to find a stick to scrape that off with before tracking it all over the Internet's carpets.


              Originally posted by WishICouldCode View Post
              Why do you think colors are not legible? In the current div they are not properly set, but they will look green and white, it should be legible. If you are not only talking about the thread div colours i'd appreciate to know your opinion about the site colors.
              There are a number of accessibility shortcomings on the site itself -- the big two are colours and font-sizes. All the font sizes are declared in PX, that's a giant middle finger to users like myself who don't use the default system metric; put simply, using small px sizes sends me diving for the zoom resulting in your layout breaking -- when if the layout had been designed using EM I wouldn't have to zoom and it would be ready to handle said scaling. EM's are based on the browser or OS default size, letting the user "set it once" and not have to screw around zooming on every blasted page. With all but a handful of corner-case exceptions, if you declare your font-size in px, you're telling a pretty large swath of potential users to go shtup themselves.

              The small sizes only further exacerbate the colour issue. You've got light greys on white, white on light green -- NONE of these meet the accessibility minimums. There's a tool that can help you figure out "yes or no" on your colours, generally speaking a properly developed page should TRY to use colours that meet WCAG 2.0 AA "normal" minimums. AAA is even better.

              WebAIM: Color Contrast Checker

              If we plug in that green and that white -- let's use the contact button's somewhat darker green... #FFFFFF on #8AB708 fails ALL tests, even "large" AA. This means that text is effectively invisibile to a quarter or more the population, and induces eye-strain for another quarter or so. The grey in your inaccessible form with the false simplicity is equally flawed. #999 is WAY too bright to go on #FFF, much less a grainy grey that ranges from #F4F4F4 to #FCFCFC... you'd use the lower number and guess what, that fails all tests too!

              Something else to consider is that the form itself is flawed thanks to that "false simplicity" I mentioned. It's using placeholder to do a label tags job, when a placeholder is NOT a label! Putting the description of the field inside the field is another giant middle finger to accessibility and should NOT be done. Even the HTML specification itself says not to do that!

              Though this article explains WHY better than any other I've seen:
              3 Types of False Simplicity - Articles - Baymard Institute

              Code issues aside, the accessibility woes are a higher priority -- you want a truly successful website you don't tell large swaths of users to sod off. The font-size choices and colour contrast? They're doing exactly that!!!
              Walk the dark path, sleep with angels, call the past for help.
              https://cutcodedown.com
              https://medium.com/@deathshadow

              Comment


              • #8
                Add this to your HTML (the span tags)

                <span id="centerdiv">
                <div class="contenedorimagenindice">
                <div class="imagenindice"><img src="http://elamigoinformatico.es/wp-content/uploads/2016/08/leagueoflegendsindiceimg.jpg" /></div>
                <div class="imagenindicemovil"><img src="http://elamigoinformatico.es/wp-content/uploads/2016/08/LOLMovil.jpg" /></div>
                <div class="contenedortutoriales">Acceder a los tutoriales</div>
                <div class="contenedorerrores">Acceder a las soluciones</div>
                </div>
                </span>

                Then add this into your CSS file

                #centerdiv
                {
                margin: auto;
                width: 500px;
                border: 1px solid blue;
                display: block;
                overflow: auto;
                }

                Comment


                • #9
                  Thank you so much for your time deathshadow

                  Comment

                  Working...
                  X