Having difficulty aligning block element in the center horizontally

I am struggling with centering elements for a list of upcoming blog posts. The Postlist component is integrated into my App.js file. Although I successfully centered the navigation bar following the method described here in the Horizontally section and specifically under the subsection named Is there more than one block level element?, I encountered difficulties when trying to apply the same approach to the list of blog posts. It should be noted that this blog post list will be dynamic in the future.

PostList.css file:

.blog-list-container {
    display: block;
    text-align: center;
    margin: 0 auto;
}

.blog-element {
    display: block;
    width: 50%;
    padding-top: 60px;
    padding-bottom: 60px;
    padding-right: 30px;
    padding-left: 30px;
}

And Postlist.js file:

import React from 'react';
import App from '../../App';
import './PostList.css';
import {
    BrowserRouter as Router,
    Routes,
    Route,
    Link,
    Outlet,
    useParams
  } from 'react-router-dom';

const PostList = ( props ) => (
    <div className="blog-list-container">
        <Router>
                <Link to={'/posts/${}'} className="blog-element">element 1</Link>
                <Link to={'/posts/${}'} className="blog-element">element 2</Link>
                <Link to={'/posts/${}'} className="blog-element">element 3</Link>
        </Router>
    </div>
);

export default PostList

Answer №1

Instead of the suggested approach, there is a more concise solution available:

.blog-element {
    display: block;
    width: 50%;
    padding: 60px 30px;
    margin: 0 auto;
}

However, I recommend utilizing flexbox:

https://codesandbox.io/s/compassionate-pare-cbjt0?fontsize=14

When reviewing your code and taking into account the suggestions provided, it's important to practice D.R.Y. coding when creating components. Here is an example:

const PostList = (props) => (
  <div className='blog-list-container'>
    <Router>
      {posts.map((post) => {
        return (
          <Link key={post.id} to={post.link} className='blog-element'>
            {post.name}
          </Link>
        )
      })}
    </Router>
  </div>
)

export default PostList

Answer №2

The behavior is in alignment with the CSS rules you have established.

.blog-element {
    display: block;
    width: 50%;
    padding-top: 60px;
    padding-bottom: 60px;
    padding-right: 30px;
    padding-left: 30px;
    margin: 0 auto; // This will centrally align it within your blog list container.
}

However, my recommendation would be to specify a max-width for the container and eliminate the width assigned to the blog element.

Answer №3

.blog-list-container {   
    text-align: center;
}
.blog-element {
    display: block;
    width: 50%;
    padding: 60px 30px;
    margin: 0 auto; // new line
}

Include this specific line in your code

or Modify your code as shown below

 .blog-list-container {   
        text-align: center;
    }
    .blog-element {
        display: block;
        padding: 60px 30px;
    }

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

Trigger a fixed bottom bar animation upon hover

I have a bar fixed to the bottom of the browser that I want to hide by default. When a user hovers over it, I want the bar to be displayed until they move their cursor away. <!doctype html> <html> <head> <meta charset="utf-8"> &l ...

Error: The Tabs component is expecting a different `value`. The Tab with the current `value` ("0") is not present in the document structure

I am encountering an issue while using MUI tabs. The error message I receive is as follows: MUI: The value assigned to the Tabs component is not valid. The Tab with this value ("0") does not exist in the document layout. Please ensure that the tab item is ...

Step-by-step guide on arranging/placing/styling two div elements next to each other

I'm facing an issue with my CSS and HTML. I can't seem to get the 2 footer items to display on the same line. Is there a problem with how I've structured my divs and styles? Any suggestions for improving the code are greatly appreciated. I& ...

NavLinkButton - add style when active or selected

I'm working with a list of NavLinks: const users = Array.from(Array(5).keys()).map((key) => ({ id: key, name: `User ${key}`, })); <List> {users.map((user) => { return ( <ListItem disablePadding key={user.id}> ...

Searching Categories with jQuery: Explore Remote Results and Cache System

Seeking to enhance user experience on my website, I have decided to implement the JQuery Category Autocomplete plugin. This will enable users to search through categorized results stored in a separate file at "/search_basic.php" (details of the file's ...

Tips on effectively centering a wide div

After much experimentation, this is what I came up with: (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en ...

Which elements should I focus on when utilizing Media Query?

For the width specified in the CSS for various tags within my HTML, do I need to individually list each tag when setting CSS for a Media Query? If so, how can I do this while maintaining the same ratio for full screen? <!DOCTYPE html PUBLIC "-//W3C//DT ...

Problem with first click in React onClick event

As a newcomer to React, I recently encountered an issue where onClick was sending an empty object to the backend on the first click. Even though I managed to resolve it, I am still curious about why this happened and what is the standard practice in such ...

Ways to deactivate remaining buttons until a function call finishes after selecting one in a react render() function?

In order to prevent the overlap of results when multiple buttons are clicked simultaneously, I need to disable all toggle buttons until one function call is complete, including the reset button. Additionally, I'm looking for a way to display my functi ...

Is there a way to detect when the mobile keyboard is open in a React application?

I am currently working with a Textfield that includes the Autofocus attribute. I am wondering if there is a method to detect when the keyboard opens in mobile view and then store this information in a boolean variable. https://i.stack.imgur.com/z0EtB.png ...

Caution: ToastAndroid is incompatible with this platform. A problem has occurred while using react native

Having trouble with this error in react native IOS: - node_modules/expo/build/logs/LogSerialization.js:166:14 in _captureConsoleStackTrace - node_modules/expo/build/logs/LogSerialization.js:41:24 in serializeLogDataAsync - ... 9 more stack frames from fra ...

When running in production, my axios requests are returning my index.html file instead of reaching my express server's API routes

After conducting some research, I discovered several posts discussing the same issue, but unfortunately none of the solutions provided worked for me. I recently developed a React app using create-react-app and also created a server.js file to incorporate ...

Having trouble resolving the module path 'fs/promises' while using Next.js and eslint

Recently, I began working on a Next.js application and successfully configured eslint to ensure code quality. Here is the list of dev dependencies for my Next.js app: "devDependencies": { "babel-eslint": "^10.1.0", &qu ...

The useState setFunction does not alter on OnClick events

My useState element is causing issues because the function doesn't get called when I click on it. I've tried multiple solutions and debugging methods, but it seems like the Click event isn't being triggered no matter what I do. const [moda ...

Components undergo a style transformation with Material UI

I've noticed that every time I render the component, the styles keep changing. import React from 'react'; import FormControl from '@material-ui/core/FormControl'; import MenuItem from '@material-ui/core/MenuItem'; im ...

Ways to evenly distribute divs into rows

Greetings if this question has already been inquired about, but my search turned up nothing quite like it. My current setup is as follows: .main{ display: inline-flex; flex-direction: row; } <div class = "main"> <div class="sub-div ...

Error: Namespace declaration does not have a type annotation - TypeScript/Babel

After creating my app using the command npx create-react-app --typescript, I encountered an issue with generated code and namespaces causing Babel to throw an error. Here are the steps I took to try and resolve the issue: I ejected the project Updated b ...

Surprising results from implementing the useLocation() hook in a React application

Currently, I am embarking on a personal endeavor to create an online auction platform. One of the key functionalities I am working on is rendering detailed product information when a user clicks on a specific product for purchase. Initially, everything wor ...

What are the distinguishing factors between using redux saga and redux thunk?

How do you know when to use redux-saga versus redux-thunk? Which one would be more suitable for an ecommerce platform? Is there a noticeable difference in performance between the two? Are thunks faster than sagas? ...

Steps to incorporate JSON data using the mapping feature of the Material-UI grid component

https://i.stack.imgur.com/tk3Hh.png I need help with adding JSON data to 4 ColorCards similar to the image provided. However, I am facing issues with rendering title`, `color`, and `rating. Please refer to the code snippet below: import ColorCard from &qu ...