What causes the text-align property to function in varying ways across different tags?

Can you explain why the text-align property behaves differently on different tags?

In two cases, I am trying to center my text. In the first case, I use a parent div tag with an anchor tag inside. When I need to center align, I apply the property to the parent.

div {
    background-color: green;
    width: 80px;
    text-align: center;
}

However, in the second case, when I use a ul as the parent with the same anchor tag inside, I have to apply the property to the anchor tag to center align the text. Why is that?

ul a {
    color: red;
    text-align: center;
}

Links to both fiddles: https://jsfiddle.net/ybnzajoo/ https://jsfiddle.net/pc939y7k/

How do I know when to write this property on the parent or the element? When should I apply text-align:center to the parent and when should I apply it to the element?

When should I apply the text-align:center property to the parent, and when should I apply it to the same element?

Answer №1

When should I apply a property to the parent and when should I apply it to the element itself?

Instead of setting the "text-align" property directly on the element you want to center, you should set it on the parent of that element.

Source: 16.2 Alignment: the 'text-align' property

Answer №2

The reason you can't achieve the same output with the same css is because the ul element automatically assigns margin and padding properties if they are not explicitly defined. To get the desired output, you can use the following code:

<style>
    div {
        background-color: green;
        width: 80px;
        margin: 16px 0;
        padding-left: 40px;
    }

    div a {
        color: red;
        text-align: center;
    }
</style>
<div>   
    <a>hello</a>
</div>

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

Customize the progress bar color in Bootstrap by setting a unique color to it

Is it possible to apply a custom color to the progress bar in Bootstrap that is not one of the standard options like success, info, warning or danger? I attempted adding the following code snippet to my bootstrap-theme.css file: .progress-bar-custom { b ...

Dealing with an endless loop caused by a promise in AngularJS's ui router $stateChangeStart event

I am currently working on implementing authentication in my Angular application and I want to redirect to an external URL when a user is not logged in (based on a $http.get request). However, I seem to be stuck in an infinite loop when using event.prevent ...

Using JSON in combination with any client or server programming language allows for seamless

Is it possible to use any language as server and client sides if I choose JSON as the data exchange format? I am currently working on a web application using PHP and jQuery. My server delivers responses in JSON format, and now I want to develop an Android ...

Tips for updating the color of table data when the value exceeds 0

I'm currently working on developing a transaction table that is intended to display debit values in red and credit values in green. However, I would like these colors to only be applied if the value in the table data is greater than 0 via JavaScript. ...

Retrieve the property value from a nested object using a key that contains spaces

Presenting my object: let obj = { innerObj: { "Key with spaces": "Value you seek" } } Upon receiving, I am unaware of the content within obj. I possess a string variable holding the key to access the value. It appears as follows: let ke ...

Dynamic <figcaption> that adjusts to different screen sizes with smooth animations

My first WordPress theme is almost complete and I'm excited to share it: The responsive image grid on the homepage is giving me some trouble. When I shrink the browser window, the images don't scale properly. The grid works fine without the JS ( ...

Count the number of URL segments using JavaScript and jQuery

Can anyone suggest an efficient method to count the number of segments in a URL using JavaScript/jQuery? For instance: www.myexampleurl.com/section1/section2/section3 should output 3 ...

Adding more dynamic parameters to the external script in index.html using Vue.js

I am looking to pass username and userEmail from the getters/user method in Vuejs, which is within index.html. Here is an example of how I would like it to be passed: <script>window.appSettings={app_id:"appId", contact_name: "Alexander ...

Is it possible to utilize the System.import or import() function for any JavaScript file, or is it restricted to single module-specific files?

After reading an intriguing article about the concept of dynamic component loading: I am interested in learning more about the use of System.import. The author demonstrates a specific syntax for loading the JavaScript file of the module that needs to be d ...

How can you use JavaScript and regex to extract the word before a comma?

Hey there, I'm attempting to extract the word right before a comma in a sentence. For instance, consider the following string: "Cloudy, and 51 ° F " I aim to retrieve CLOUDY as the output. Could someone guide me on how to achieve this using regex ...

Using JavaScript to pass a newly created variable as an argument in a default

Currently, I am developing a node application that heavily utilizes promises. To enhance the readability of my code, I have been removing anonymous functions and storing them in a JavaScript object called "myCallbacks". Here's an example: let myCallb ...

Utilizing Zebra Printers for Seamless Integration and Printing in Ext Js

I'm currently working on developing an app in ExtJs that involves printing a PDF label for warehouse purposes using Zebra smartphones connected to printers via Bluetooth. I've been trying to implement Zebra's APIs specifically the BrowserPri ...

Congratulations! Your product has been successfully added to Magento using Ajax

While using Firebug, I discovered that JSON generates a message within the success function. However, I am having trouble figuring out how to display it. As a workaround, I attempted to add the following code snippet: if(data.status == 'ERROR'){ ...

What is the best way to vertically center a caption when an image is being hovered over

I'm facing an issue with aligning my caption vertically inside a div when hovering. The image within the div is larger than the div, and I want the caption to be at the center of the div. HTML <div class="container-fluid"> <div id="pag ...

Steps to combine multiple arrays into a unified array:1. Begin by allocating a

To form a league table, I have multiple individual arrays filled with data. In order to sort them by points, I want to merge these arrays into a single array called "teams". However, I am unsure if there is a function available to achieve this specific f ...

Overlapping Flexbox elements causing stacking issues

My attempt to create a gallery layout with two larger blocks amidst smaller blocks is not functioning correctly. The large block is overlapping the two smaller blocks below it. Is there a way to prevent block overlapping using CSS? I have searched Stack O ...

Various text sizes within a nested HTML list structure

I've developed a nested CSS class for an ordered list on my website, but I'm encountering a problem where each list item is appearing in different font sizes even though I have specified the font size. .number_list ol { font:normal 1.2em ...

Is there a way to specify the login response details when making an Angular API request?

I am currently using Angular to connect to my backend login service. However, I am facing an issue with setting the popup message when the username or password is incorrect. I want to display the detailed message from the API on my login page when any erro ...

Tips for implementing Vue in production mode with vue.esm-bundler.js

Currently, I am utilizing Vue 3 with webpack and loading it using vue.esm-bundler.js due to the presence of in-dom templates. The documentation mentions that when using a bundler, you need to "Leaves prod/dev branches with process.env.NODE_ENV guards (mus ...

The NodeJS nedb function seems to be ignoring the await keyword

The time it takes for the function checkExists to run is too lengthy. Despite attempting to implement await and async functions, using var exists = await checkExists(data.email); still results in undefined value due to not properly awaiting for checkExists ...