Tips for centering a div vertically inside another div that has a background image

My goal is to center the text within the background image, keeping it centered on all devices. Initially, I used a fixed pixel margin-top value, but I need it to be a percentage so that it remains centered as the screen size changes. However, when I changed the margin to a percentage, the text would shift upwards when the screen was minimized. I want the text to always stay 50% from the top of the background picture.

HTML

  <div class='bg'>
      <div class='bg-text'>
        <h1>Text</h1>
      </div>
    </div>

CSS

.

.bg {
  display: table; 
  width: 100%;
  height: 50%;
  background-image: image-url('pic.jpg');
  background-attachment: scroll;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
}

.bg-text{
  color: #fff;
  text-align: center;
  text-shadow: 1px 1px 12px rgba(0,0,0,0.5);
  margin-top: 150px;
}

.bg-text h1{
    font-size: 50px;
    font-weight: 700;
}

Answer №1

To center the inner div, use the flex property.

.bg {
  display: flex;
  align-items:center;
  width: 100%;
  height: 300px;
  background-image: url('pic.jpg');
  background-attachment: scroll;
  background-color: red;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
}

.bg-text{
  color: #fff;
  text-align: center;
  text-shadow: 1px 1px 12px rgba(0,0,0,0.5);
}

.bg-text h1{
    font-size: 50px;
    font-weight: 700;
}

Take a look at the example here: https://jsfiddle.net/pteus556/

This code is supported in various browsers.

https://i.sstatic.net/SFASJ.png

Answer №2

Another approach to achieve this effect is by utilizing transform: translateY(-50%);. Feel free to explore the demonstration in this fiddle: https://jsfiddle.net/y58hu6tv/2/.

.bg {
    width: 100%;
    height: 500px;
    background-color: rgba(0, 0, 0, .7);
}

.bg-text {
   position: relative;
   top: 50%;
   margin: 0 auto;
   transform: translateY(-50%);
   text-align: center;
   background-color: rgba(255, 255, 255, .7);
}

However, keep in mind that browser support for this method may vary.

https://i.sstatic.net/9j8la.png

For more information, check out the following reference link: http://caniuse.com/#feat=transforms2d

Answer №3

  • Design a <div> with specific dimensions and incorporate your chosen background.
  • Customize the size of the <div> to fit your requirements.
  • Insert your text within the designated <div>.

  • Align the text within the <div> using position:absolute - relative to its parent.

  • Utilize the transform property along with top / left / right / bottom for positioning.

.mycontent {
  width: 100vw;
  max-width: 100%;
}
.mytext {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: absolute;
  background: rgba(255, 255, 255, .6);
  border: 1px solid #777;
  padding: .2em;
  color: #000;
}
.topcontent {
  height: 100vh;
  width: 2560px;
  max-width: 100%;
  background: url(http://supersocl.com/wp-content/uploads/2016/09/2560X1440-Wallpaper-Elegant-6G0.jpg);
  background-size: cover;
}
.othercontent {
  background: #010101;
  padding: 30px;
}
body {
  max-width: 100%;
  padding: 0;
  margin: 0 auto;
  color: #999;
}
p {
  margin: 0 auto;
  padding: 20px;
  text-align: justify;
  text-justify: inter-word;
}
<body>
  <div class="mycontent">
    <div class="topcontent">
      <span class="mytext">insert your text here</span>
    </div>
    <div class="othercontent">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed laoreet eleifend nunc, ac luctus enim rutrum in. Nullam imperdiet purus id ante vestibulum fermentum.</p>

      <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vivamus varius pretium orci ut semper. Fusce nec sagittis justo, eget porta lectus. In hac habitasse platea dictumst.</p>

      <p>Quisque dapibus eros sed tortor lobortis, vel pulvinar magna dapibus. Phasellus feugiat arcu nibh, nec fermentum urna condimentum vel. Proin ultricies ultrices dui nec fringilla. Quisque non libero eu ex dignissim pharetra.</p>;

      <p>Etiam cursus, elit ac finibus aliquam, est felis vehicula sapien, ac tincidunt nulla erat nec tellus. Suspendisse potenti. Nunc eget augue tristique, consequat mauris sed, vehicula nisl. Nam placerat scelerisque diam eget convallis.<
       </p>
    </div>
  </div>
</body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attempting to submit a form containing multiple fields that share the same name as an array

I am attempting to submit a form with fields that function as entries in a table For clarity, here is an example: <form method="post"> <table> <tr> <td><label>Name:</label></td> ...

Can the title of href links be concealed?

<a href="link.html" title="Titletext"> ...is the code. I have a requirement to utilize the title attribute due to using slimbox, however, I am looking for a way to conceal the title text that appears when hovering over the link. Does anyone have a ...

What is the process for determining the overall cost of a column in Angular 9?

I am facing a challenge in calculating the total price, total quantity, and total counted(#) of each column in a table. | Item | Price | Quantity | 1 | Mouse | 500 | 1 | 2 | Wire | 100 | 2 | TI:3 | |TP:600 | TQ:3 | < ...

What is the best way to use jQuery to toggle the hidden class on an inner div when a button inside a card is clicked?

How can I implement jQuery functionality to toggle the hidden class on an inner div by clicking a button inside a card? I attempted to create a container div containing multiple cards. The issue arises when I click the button - it only opens the panel, bu ...

Replace the placeholder text with an icon

I am having trouble changing the placeholder text using a function. I am unable to add any additional code to style the text, such as making it bold or adding an icon next to it. When I try to do so, the code is displayed as text instead of being executed. ...

Determine if the chosen option is present in any of the four arrays using Jquery/HTML, and execute a specific function based

I've been searching the web and other questions for assistance with this, but I can't seem to figure it out. I suspect that I'm not using the correct keywords. My goal is to create a functionality based on a value selected by a user from a ...

If I needed to include extra information within an element for easy retrieval using JavaScript

Using PHP, I have generated a list of products in a <select> element. Each product has a weight that I want to store within each <option> so I can access it later using Javascript. Is there a way to include the weight data directly in the HTML ...

Adjust iFrame to allow scrolling dynamically

I am currently facing a challenge with creating a non-scrollable iframe element using JavaScript. The function I need to call is within an iframe, and while it works on Firefox and Chrome, I also need it to work on Internet Explorer. My solution involves ...

Scroll automatically when dragging the mouse

My D3 tree creation is causing an issue with the horizontal scroll bar in Firefox 37. When trying to drag select a tree node, the horizontal scroll bar does not work. However, in Chrome, the horizontal scroll works fine during drag selection. <div cl ...

Is the fixed header see-through?

I have a query regarding my website design. Currently, the fixed header on my site is transparent and when I scroll down, the content overlaps the header. However, I want the header to remain above the content. Can anyone provide assistance with this issue ...

What is an html5 tooltip widget?

I stumbled upon a helpful tutorial on html5canvastutorials.com that caught my eye: let triangle = new Kinetic.Shape(function(){ let ctx = this.getContext(); ctx.beginPath(); ctx.lineWidth = 4; ...

Is it possible to supersede the pre-set validation of the html5 input types for url and email?

When using the input type url in html5, what are the default rules for a valid URL? If a custom pattern attribute is also specified along with the type, will it override the default validation rules? For example, in the line below, will the pattern attribu ...

Leveraging the jQuery method .stop() to halt solely the .fadeTo() animation

My webpage features two jQuery effects applied to a <div>. Using the animate() function, I move it left and right, while utilizing fadeTo() to fade it out when the mouse is not hovering over the <div>. To prevent multiple fading effects caused ...

Webpage created from scratch encounters technical difficulties on mobile device browser

My website seems to be getting stuck at the beginning of a section, particularly on mobile browsers. You can check out the website here <section class="home-slider owl-carousel"> <div class="slider-item" style="background-image: url(images/bg ...

Dealing with ng-repeat and button alignment across Chrome, Edge, and Firefox

Can someone help me understand this strange behavior I am experiencing across all browsers? <div style="margin-top:5px"> <button translate="clear" ng-click="xyz.clear()" class="btn btn-default"></button> <butt ...

The system is unable to retrieve the value of the property which is set as null

I'm trying to figure out how to store the input value of name_enter into the variable userName. However, every time I attempt this, I encounter the following console error: Uncaught TypeError: Cannot read property 'value' of null function ...

Having trouble loading the image source using JSON in Vue.js

var topArticle=new Vue({ el:'#toparticle', data:{topmostArticle:null}, created: function(){ fetch('topnews.json') .then(r=>r.json()) .then(res=>{this.topmostArticle=$.grep(res,functi ...

Having trouble getting the Vue.js framework to function properly on a basic HTML page with a CDN implementation

I recently delved into learning vue.js and decided to focus on forms. However, when I tried to open the file using a live server or XAMPP, it didn't work as expected. It had worked fine before, but now I seem to be encountering some issues. Could anyo ...

Adding an HTML arrow icon within a button

As I work on creating an HTML email, my aim is to incorporate a right arrow onto an HTML button. To achieve this, I have opted to utilize a special character and apply the transform-rotate property. However, I am facing an issue where the text and arrow a ...

Is it possible to create a dynamic image in WordPress and have it automatically set as the background in the Style.css file?

I successfully transformed an HTML template into a WP theme and now I aim to add dynamic elements throughout. My first task is to make the slider (comprised of image, heading, content, button) dynamic. Currently, all the code resides in index.php except ...