Christian M. Christian M. - 4 months ago 9
HTML Question

Can't center text HTML / CSS

I'm VERY new to web development and I decided to work on a small project for practice. I've spent the last 30 minutes trying to center the "Where creativity lives" text directly below the logo and text but it's being difficult and not working, could anyone help? Also, if you have any tips with what I've made so far, I'd greatly appreciate it thanks!

Here it is:



div.header {
margin-left: auto;
margin-right: auto;
width: 440px;
display: block;
}

h1 {
font-family: 'Raleway', sans-serif;
text-align: center;
font-size: 100px;
margin-top: auto;
color: #27ae60;
}

h2 {
font-family: 'Source Sans Pro', sans-serif;
text-align: center;
}

#logo {
width: 100px;
}

<!-- begin snippet: js hide: false console: true babel: false -->

<!DOCTYPE html>
<html>
<head>
<title>Reacts</title>
<link href="styles.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Raleway|Source+Sans+Pro" rel="stylesheet">
</head>

<body>

<div class=header>
<h1 style="float: right;">Reacts</h1>
<img id="logo" style="float: left;" src="Logo.png">
</div>

<h2>Where creativity lives.</h2>

</body>
</html>




Answer

When you're using float, it puts all other elements that aren't floating in the remaining space. If you want it to instead appear below the floated elements, use clear: both

div.header {
    margin-left: auto;
    margin-right: auto;
    width: 440px;
    display: block;
}

h1 {
    font-family: 'Raleway', sans-serif;
    text-align: center;
    font-size: 100px;
    margin-top: auto;
    color: #27ae60;
}

h2 {
    font-family: 'Source Sans Pro', sans-serif;
    text-align: center;
    clear: both; /* <---- Added this */
}

#logo {
    width: 100px;
}

<!-- begin snippet: js hide: false console: true babel: false -->
<!DOCTYPE html>
<html>
<head>
    <title>Reacts</title>
    <link href="styles.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Raleway|Source+Sans+Pro" rel="stylesheet">
</head>
    
<body>

<div class=header>
<h1 style="float: right;">Reacts</h1>
<img id="logo" style="float: left;" src="Logo.png">
</div>

<h2>Where creativity lives.</h2>
    
</body>
</html>

Comments