hteml
hteml

Reputation: 43

How can I properly align header with centered div element?

I want the header to align at the top-left-corner of the centered div element. The only way I can think of doing this is setting position to relative and using top with a value of 20%. The problem with this is that it causes the header to stretch the page further to the right as can be see in the fiddle.

body {
  font-family: Europa;
}

.header {
  position: relative;
  left: 20%;
  display: block;
  margin-left: auto;
  margin-right: auto
}

h4 {
  font-size: 5em;
  margin: 0 auto;
}

.box {
  height: 500px;
  width: 500px;
  position: relative;
  border-radius: 20px;
  background: #6441a5;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}
<div class="header">
  <h4>header</h4>
</div>

<div class="box">
</div>

Upvotes: 2

Views: 38

Answers (4)

theAlexandrian
theAlexandrian

Reputation: 908

The simplest solution is to put your two elements in one div, like this:

body {
  font-family: Europa;
}

.header {
    display: block;
    margin: auto;
    width: 500px;
}

h4 {
  font-size: 5em;
  margin: 0 auto;
}

.speech-bubble {
  height: 500px;
  width:500px;
  position: relative;
  border-radius: 20px;
  background:#6441a5;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
    <div class="header">
        <h4>header</h4>

        <div class="speech-bubble">

        </div>
    </div>

Upvotes: 0

Julio Feferman
Julio Feferman

Reputation: 2676

Simply give your header block the same width as your box.

body {
  font-family: Europa;
}

.header {
  position: relative;
  width:500px;
  display: block;
  margin-left: auto;
  margin-right: auto
}

h4 {
  font-size: 5em;
  margin: 0 auto;
}

.box {
  height: 500px;
  width: 500px;
  position: relative;
  border-radius: 20px;
  background: #6441a5;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}
<div class="header">
  <h4>header</h4>
</div>

<div class="box">
</div>

Upvotes: 1

SLL
SLL

Reputation: 271

Try giving your header h4 the same width as your speech-bubble: https://jsfiddle.net/hxjdy720/

 h4 {
  font-size: 5em;
  margin: 0 auto;
  width: 500px;
}

Upvotes: 0

Ryan Parrish
Ryan Parrish

Reputation: 106

Using a .centered wrapping div you can more easily obtain your desired results w/ keeping the elements fluid if wanted.

<div class="centered">
  <h4>header</h4>
  <div class="speech-bubble"></div> 
</div>

<style>
h4 {
  font-size: 5em;
  margin: 0 auto;
}

.speech-bubble {
  height: 500px;
  width: 100%;
  border-radius: 20px;
  background:#6441a5;
  margin: auto;
}
.centered{
  width:500px;
  margin: 0 auto;
  position: relative;
}

</style>

Upvotes: 0

Related Questions