HiveBrain v1.2.0
Get Started
← Back to all entries
patternhtmlMinor

Vertically and horizontally center these HTML elements

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theseelementshorizontallyverticallycenterandhtml

Problem

I have an image and a text title that I'm trying to center in a div. I would like the image to be to the left of the title, and for both of these elements to be centered both horizontally and vertically in the div.

I've found one way to do it, by nesting the image inside of a paragraph. I'm assuming this is not the proper way to do it, but I haven't been able to figure out any other way.

Here is a jsfiddle: http://jsfiddle.net/FvpV3/

And here is the code:


    

        

            

                

                    
                        
                    

                    Title

                

            

            

                message

            

        

    


Does anyone know of a better way to position the image and title?

Solution

You can simplify your HTML to this:


    
    Title
    $message


By adding classes, you can re-use CSS on more than one HTML element. The class floaters is applied to both of the divs that make up the top line. The class right is only applied to the left div on the first line to make it right aligned.

The #parent:after is one example of a clearfix. There are several other versions of clearfixes.

* {
    box-sizing: border-box;
}
#parent {
    margin: 0px auto;
    width: 50%;
    border-radius: 6px;
    border: 1px solid #CFCFCF;
}
#parent:after {
  content: "";
  display: table;
  clear: both;
}
.floaters {
    float: left;
    background-color:#E4E4E4;
    width: 50%;
    height: 3em;
    padding: 5px 12px 5px 0;
}
.right {
    text-align: right;
}
.centerme {
    float: left;
    clear: both;
    text-align: center;
    background-color:#EFEFEF;
    height: 3em;
    width: 100%;
    padding-top: 12px;
}


I have a working jsfiddle for you to look at.

Code Snippets

<div id="parent">
    <div class="floaters right"><img src="cid:logo-img" /></div>
    <div class="floaters">Title</div>
    <div class="centerme">$message</div>
</div>
* {
    box-sizing: border-box;
}
#parent {
    margin: 0px auto;
    width: 50%;
    border-radius: 6px;
    border: 1px solid #CFCFCF;
}
#parent:after {
  content: "";
  display: table;
  clear: both;
}
.floaters {
    float: left;
    background-color:#E4E4E4;
    width: 50%;
    height: 3em;
    padding: 5px 12px 5px 0;
}
.right {
    text-align: right;
}
.centerme {
    float: left;
    clear: both;
    text-align: center;
    background-color:#EFEFEF;
    height: 3em;
    width: 100%;
    padding-top: 12px;
}

Context

StackExchange Code Review Q#42717, answer score: 2

Revisions (0)

No revisions yet.